POST请求未填充正文

时间:2019-11-04 22:10:35

标签: javascript express

我无法从客户端向服务器端发送信息。

在我的应用程序中,我有一个要提交到服务器的表单。因为我正在使用一个lib从json模式文件自动生成表单,所以我将不得不手动提交表单,基本上是用我的对象发出一个post请求。到目前为止一切顺利,但是我的请求到了后端却空着了。

客户发布请求:

const test = {
    name: "hello"
}
axios.post("http://localhost:8000/my-route/test", test)
    .then(res => console.log("res.data", res.data));

服务器路由定义

app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
app.use(cors());

/* ... */

app.post("/my-route/:type", (req, res) => {
    if (!req.params.type) {
        res.send({
            err: "Please provide type"
        });
    } else {
        console.log('req.body', req.body);

        res.send({
            sucess: "Generating type " + req.params.type
        });
    }
});

我在后端的日志生成req.body {}而不是req.body { name: "hello" }

如果我决定JSON.stringify(test),那么我的日志将变成req.body { '{"name":"hello"}': '' },这并不是我真正想要的。

1 个答案:

答案 0 :(得分:1)

axios请求正在发送JSON有效负载。但是,您的服务器没有解析JSON。它只是解析URL编码的主体。您将要添加此中间件:

app.use(bodyParser.json());

由于没有该解析器,因此bodyParser.urlencoded(...)中间件只用空对象填充req.body