-1

I want try to retrieve data from my frontend via the DOM to the backend and I don't know how to do it. I used a POST to console.log the datas but how to retrieve it in my Express backend ? (The console.log works well)

My JS:

let urlSave = hitsItem.querySelector('.link-item').href;
            let imgSave = hitsItem.querySelector('.infinitehits__img').src;
            let marqueSave = hitsItem.querySelector('.hit__marque').textContent;
            let smSave = hitsItem.querySelector('.hit__sous_modele2').textContent;
            let typeSave = hitsItem.querySelector('.hit__type').textContent;
            let yearsSave = hitsItem.querySelector('.hit__year_interval').textContent;
            let coteEuSave = hitsItem.querySelector('.cote_actual_eu').textContent;
            let coteUsdSave = hitsItem.querySelector('.cote_actual_usd').textContent;
            let coteGbSave = hitsItem.querySelector('.cote_actual_gb').textContent;
            let coteChfSave = hitsItem.querySelector('.cote_actual_chf').textContent;
let modelSave = {
                        urlSave: urlSave,
                        imgSave: imgSave,
                        marqueSave: marqueSave,
                        smSave: smSave,
                        typeSave: typeSave,
                        yearsSave: yearsSave,
                        coteEuSave: coteEuSave,
                        coteUsdSave: coteUsdSave,
                        coteGbSave: coteGbSave,
                        coteChfSave: coteChfSave
                    }
                    //console.log(modelSave)
                    // Get datas to save
                    $.post('/fr/save', () => {
                        console.log(modelSave);
                    })

My node backend:

router.post('/save', ensureAuthenticated, (req, res) => {
    res.send('yep')
})

router.get('/save', ensureAuthenticated, (req, res) => {
    res.send('yep')
})
lf_celine
  • 653
  • 7
  • 19
  • https://stackoverflow.com/questions/6158933/how-is-an-http-post-request-made-in-node-js – Taki Feb 24 '20 at 16:19

1 Answers1

1

Step 1. Actually send the data to the backend:

$.post( '/fr/save', modelSave );

Step 2. Do something with it on the backend:

router.post('/save', ensureAuthenticated, (req, res) => {
    console.log(req.body)
    res.send('yep')
})

Make sure you have the Express json bodyparser middleware loaded:

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/json
app.use(bodyParser.json())
Josh Wulf
  • 4,727
  • 2
  • 20
  • 34
  • You are most welcome! One suggestion, if I may. Those assignments look like they should be `const`. See [this article](https://www.joshwulf.com/blog/2020/02/shun-the-mutant/). – Josh Wulf Feb 26 '20 at 10:29
  • Indeed, I always use `const` in these cases – lf_celine Feb 26 '20 at 10:32