1

不幸的是,当我通过(配置表单标题)向我的 api 发送一些东西body: {}时,我在请求对象中得到了一个空:POSTInsomniaForm URL EncodedContent-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 配置为 Form as JSON, Header ,我还需要在我的代码中进行哪些更改Content-Type: application/json

4

2 回答 2

1

在 Express v4.16.0 及以后版本中可用:

app.use(express.urlencoded({ extended: false }));
app.use(express.json());
于 2018-11-27T16:27:18.313 回答
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}...`));
于 2018-11-27T15:46:52.290 回答