【问题标题】:How do I access the data in a POST request in express?如何以快递方式访问 POST 请求中的数据?
【发布时间】:2015-10-23 15:05:15
【问题描述】:

这是我的客户端代码:

  $.post("/audio",
    {
      type: 'instrumental',
      name: 'Instrumental_30SecondsToMars_TheKill'
    },
    function(data, status) {
      alert("Data: " + data + "\nStatus: " + status);
    });

这是我的服务器端代码:

app.post('/audio', function (req, res) {
  console.log(req.body);
});

如何从服务器端函数访问我在帖子中发送的类型和名称?

它肯定会被调用,因为服务器是控制台日志记录。

【问题讨论】:

    标签: javascript post express client server


    【解决方案1】:

    你需要使用像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 }))
    
    app.post('/audio', function (req, res) {
      console.log(req.body); // <-- now has req.body.type, req.body.name
    });
    

    【讨论】:

      【解决方案2】:

      需要用到bodyparser中间件:

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

      然后

      app.use(bodyParser.json());
      app.use(bodyParser.urlencoded({ extended: true }));
      

      【讨论】:

        猜你喜欢
        • 2011-09-17
        • 1970-01-01
        • 2016-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-02
        • 2018-05-10
        • 2014-01-31
        相关资源
        最近更新 更多