1

When I send data from Angular to NodeJS using http.post, it always returns me empty req.query. My server.js:

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');

const app = express();

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

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

app.listen(4000, () => {
    console.log('Successfully');
});

Frontend:

onSubmit(f: NgForm) {
    let data = f.value;
    let httpOptions = {
        headers: new HttpHeaders().set('Content-Type', 'application/json')
    };
    data = JSON.stringify(data);
    this.http.post('http://localhost:4000/', data, httpOptions).subscribe(data => {
        console.log(data);
    }, error => {
        console.log(error);
    });
}

And it always returns {} in console. I tried to run POST-requests in POSTMAN and it correctly worked there. Here is the body of http-request in browser: http-request in browser

Hope for your help, thanks.

1
  • What about if you directly append to the URL in the front end as a query string? Commented Dec 21, 2018 at 2:01

3 Answers 3

2

That's because req.query holds the query string parameters, looks like you are only passing data up via the body so you want req.body

Sign up to request clarification or add additional context in comments.

Comments

0

You're using req.query but you're sending data in the body, not as query parameters.

Try using req.body instead.

Comments

0

You will recive data in body , i.e req.body. Where as for query your api will look like http://localhost:4000/yourEndPoint?id=XX

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.