简体   繁体   English

如何快速访问POST请求中的数据?

[英]How do I access the data in a POST request in express?

Here's my client side code: 这是我的客户端代码:

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

And here's my server side code: 这是我的服务器端代码:

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

How do I access the type and name that I sent in the post from within the server side function? 如何从服务器端功能中访问帖子中发送的类型和名称?

It's definitely being called as the server is console logging. 肯定是因为服务器是控制台日志记录而被称为。

You need to use the bodyparser middleware: 您需要使用bodyparser中间件:

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

and then 接着

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

You need to use a parsing module like body-parser 您需要使用诸如body-parser之类的解析模块

Use like this: 像这样使用:

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
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM