0

In my app.js file in Node.js I have this:

app.use(express.json()); 

which I thought was good enough but whenever I submit data via jQuery/Ajax the response is an empty object.

After doing the below however, it now get the data from req.body. But, I thought that in the newer versions of Express it was not necessary to do this anymore?

const bodyParser = require("body-parser");

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

The Ajax request:

    $.ajax({
        url: 'http://localhost:8000/api/v1/endpoint',
        method: 'POST',
        data: {key: key}
    })
    .done(function(data) {
        console.log(data)
    })
    .fail(function(data) {
        console.log(data);
    })
2
  • both .json and .urlencoded are implemented, but you still need to do app.use(expess.json()) see docs expressjs.com/en/api.html, sidenote, dont hardcode http://localhost:8000 in your ajax call Jul 27, 2022 at 17:55
  • @LawrenceCherone yes, I am already using app.use(express.json()); but as mentioned the response is empty. Only when I add the bodyParser code do I then get the actual response. Are you saying I still need to do the bodyParser as well as app.use(express.json()); ie: I have to have both? When using React I don't need bodyParser included. Thanks for the sidenote, it was just for this example, I won't hardcode it in production. Jul 27, 2022 at 17:57

1 Answer 1

3

The issue is with how you're making your ajax requests. express.json expects the Content-Type of the request to be JSON and I believe if you check your network call on the browser DevTools you'll see that the Content-Type of your request is not JSON.

You need to set the headers in your ajax request and also send valid JSON data like so

headers: {
    'Content-Type': 'application/json',
},
data: JSON.stringify({key: key})

Then the express.json middleware will handle the request and you won't need to use the bodyParser lines of code you're using.

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.