0

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

1 Answer 1

1

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));
Sign up to request clarification or add additional context in comments.

2 Comments

Hi! I made it work by adding setRequestHeader and removing the 'data=' in the send method, however, I still had to keep the JSON.stringify(searchConditions) and not just searchConditions like you mentioned, if you could elaborate on that and edited your answer, I would gladly accept this as the solution, thanks.
Oh, okay. Haven't worked with plain XHR requests in a while. I corrected it, my bad!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.