快递js - 请求正文为空

maz*_*azy 2 javascript node.js express body-parser

我刚刚安装了最新版本的模块.我无法获得任何GET或POST变量.我做错了什么?节点:v0.12.2

var express        =         require("express");
var bodyParser     =         require("body-parser");
var app            =         express();
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

app.use(function (req, res) {
    res.setHeader('Content-Type', 'text/plain')
    res.write('you posted:\n')
    res.end(JSON.stringify(req.body, null, 2))
});
app.listen(3000,function(){
    console.log("Started on PORT 3000");
})
Run Code Online (Sandbox Code Playgroud)

http:// localhost:3000 /?token = devvvvv GET返回:你发布了:{}

谢谢你的答案,但POST的问题没有解决...在http:// localhost:3000上的POST令牌= as123ds /在req.body中返回空数组我该如何解决这个问题?

nor*_*gen 6

您正在通过查询字符串提交参数,并尝试通过请求正文访问它们,在这种情况下,请求正为空.

token参数将在request.query中可用,如下所示:

app.use(function (req, res) {
  res.setHeader('Content-Type', 'text/plain')
  res.write('you posted:\n')
  res.end(JSON.stringify(req.query.token, null, 2))
});
Run Code Online (Sandbox Code Playgroud)

如果您只打算在查询字符串中提交参数,则根本不需要安装正文解析器中间件.