简体   繁体   中英

Empty req.query on ExpressJS

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.

那是因为req.query拥有查询字符串参数,看起来您只是通过主体传递数据,所以您需要req.body

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

Try using req.body instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM