Home > Blockchain >  ajax requests to Node.js
ajax requests to Node.js

Time:07-28

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);
    })

CodePudding user response:

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.

CodePudding user response:

Using GitHub Copilot gives the answer:

// create an express app that uses a json body
app.use(express.json());
  • Related