代码之家  ›  专栏  ›  技术社区  ›  sunwarr10r

使用Nodejs express发布

  •  0
  • sunwarr10r  · 技术社区  · 7 年前

    不幸的是我空了 body: {} 在请求对象中,当 POST 通过 Insomnia (配置表 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}...`));
    

    我做错什么了?如果将失眠配置为 JSON ,标题 Content-Type: application/json ?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Rahul Sharma    7 年前

    用于访问请求正文 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
  •  1
  •   maxkvoronin    7 年前

    在Express v4.16.0以后的版本中提供:

    app.use(express.urlencoded({ extended: false }));
    app.use(express.json());
    
    推荐文章