【问题标题】:POST with Nodejs express使用 Nodejs 快速发布
【发布时间】:2018-11-27 15:44:42
【问题描述】:

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

【问题讨论】:

    标签: node.js express post insomnia


    【解决方案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}...`));
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 但是如何解析Content-Type: application/json?这个还是不行。
      • 只是不要包含app.use(express.urlencoded({ extended: false }));这一行
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-07
      • 2018-09-27
      • 2017-12-18
      相关资源
      最近更新 更多