securenova
securenova

Reputation: 502

How to retrieve data on server side with node.js sent by frontend ajax via post method?

I recently started learning node.js with express framework and stumbled upon a problem.

I'm trying out a simple query search webapp and I want to pass a piece of data(a boolean called all)

from front-end plain javascript via ajax to the server side, but the current code

that I have written as of right now, it seems that my data was not passed to the server side,

the 3 console.log that I planted all return {}.

What concept am I missing here? What am I doing wrong?

If any additional info is needed, pls let me know, Thanks.

front end js

window.onload=function(){
console.log("window loaded");
const xhr = new XMLHttpRequest();
xhr.open("POST","http://127.0.0.1:3000/search", true);
xhr.onreadystatechange = function(){
    if(xhr.readyState === 4 && xhr.status==200){
        // code later to be implemented
    }
}
let searchConditions = new SearchConditions(true);
console.log('data='+JSON.stringify(searchConditions));
xhr.send('data='+JSON.stringify(searchConditions));
}

class SearchConditions{
    constructor(all) {
        this.all = all;
    }
}

backend node.js

// only partial code

const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

app.post('/search', (req, res) => {
    console.log(req.body);
    console.log(req.query);
    console.log(req.params);
});

my browser log

enter image description here

my backendlog

enter image description here

Upvotes: 0

Views: 108

Answers (1)

Chris Pi
Chris Pi

Reputation: 612

Because you send invalid data:

xhr.send('data='+JSON.stringify(searchConditions));

JSON Objects do not have variable declarations. What your Server gets is:

'data = {"all": true }'

This is not even a valid variable declaration. What your server should get is:

{"all": true}

Try to send the plain JSON Object without a variable declaration and set the "Content-Type"-header to json:

xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify(searchConditions));

Upvotes: 1

Related Questions