0

Hi I have been dealing with a problem with my Express server. There have been many Stack Overflow posts on this problem but I have been unable to find an answer that works for me. When receiving a POST request, I am only getting {} for request.body in the code below:

const bodyParser = require('body-parser');
const app = express();
const User = require('./models/users');
const port = process.env.PORT || 3000;

app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json()); // support json encoded bodies

//Basic routes
app.post('/signup', async (request,response)=>{
    //const newUser = new User(queryObject);
    console.log("in post");
    console.log(request.body);
    response.end();
});


//Binding to a port
app.listen(port, ()=>{
    console.log('Express server started at port 3000');
});

This is where I am sending the POST request:

const xhr = new XMLHttpRequest();
            xhr.addEventListener('load', () => {
                console.log(xhr.response);
            });
            xhr.open('POST', 'http://localhost:3000/signup', false);
            xhr.send(JSON.stringify({ hello : "WORLD" }));

Is there something that I am missing or doing wrong? Thank you.

2 Answers2

0

Yoy are not sending anything back to client, So Pass your json object inside res.end() or use this res.json({"foo": "bar"});

  • Thank you for the answer. I changed **response.end();** to **response.send({ 'foo' : 'bar' });** but it still does not work. I am still getting an empty request body. – Snoop Choi May 05 '20 at 20:23
0

Did you check the browser's console? You should see the error like this one:

Access to XMLHttpRequest at 'http://localhost:3000/signup' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Also, did you check this answer?

Update:

Since you have no CORS related errors, then just set the header:

xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify({ hello: "WORLD" }));

Express will recognize it as JSON and it will be available as req.body.

  • I am not being blocked by CORS policy as I have set my Access-Control-Allow-Origin header and I am not getting anything in the browser's console. I checked that answer out and I think I am having a different problem since I am not getting any error message. Thank you though. – Snoop Choi May 05 '20 at 20:39
  • Don't post comment as answer – Mickael B. May 05 '20 at 20:57
  • It is a good idea to mention this as well. Because I just copy-pasted your code and got a CORS error – Nathan Crawford May 05 '20 at 21:39
  • I am using an extension to allow for CORS errors. But adding that Request Header fixed it thank you very much. – Snoop Choi May 09 '20 at 21:05