POST与Node.js Express

时间:2018-11-27 15:44:43

标签: node.js express post insomnia

不幸的是,当我通过body: {}(配置表格POST标头Insomnia)向我的api Form URL Encoded到我的api时,我在请求对象中得到一个空的Content-Type: application/x-www-form-urlencoded

这是我的快递代码:

const express = require('express');
const app = express();
app.use(express.json());

app.post('/api/', function(req, res) {

    test = req.body.test;
    console.log(req);
    console.log(test);
    res.send("Hallo");
});

const port = 4000;
app.listen(port, () => console.log(`Listening on port ${port}...`));

我在做什么错?如果将Insomnia设置为JSON,标题Content-Type: application/json,我还需要在代码中进行哪些更改?

2 个答案:

答案 0 :(得分:1)

要访问请求正文,请使用body-parser middleware,并以JSON格式发送响应,请使用res.json()

https://www.npmjs.com/package/body-parser

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

app.post('/api/', function(req, res) {
    test = req.body.test;
    console.log(req);
    console.log(test);
    res.json({"message":"Hallo"}); //update here
});

const port = 4000;
app.listen(port, () => console.log(`Listening on port ${port}...`));

答案 1 :(得分:1)

在Express v4.16.0及更高版本中可用:

app.use(express.urlencoded({ extended: false }));
app.use(express.json());