Javascript 如何检索POST查询参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5710358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to retrieve POST query parameters?
提问by murvinlai
Here is my simple form:
这是我的简单表格:
<form id="loginformA" action="userlogin" method="post">
<div>
<label for="email">Email: </label>
<input type="text" id="email" name="email"></input>
</div>
<input type="submit" value="Submit"></input>
</form>
Here is my Express.js/Node.js code:
这是我的Express.js/Node.js 代码:
app.post('/userlogin', function(sReq, sRes){
var email = sReq.query.email.;
}
I tried sReq.query.email
or sReq.query['email']
or sReq.params['email']
, etc. None of them work. They all return undefined
.
我试过sReq.query.email
orsReq.query['email']
或sReq.params['email']
等。它们都不起作用。他们都回来了undefined
。
When I change to a Get call, it works, so .. any idea?
当我更改为 Get 调用时,它可以工作,所以.. 知道吗?
回答by Drew Noakes
Things have changedonce again starting Express 4.16.0, you can now use express.json()
and express.urlencoded()
just like in Express 3.0.
事情已经改变了再次启动快速4.16.0,您现在可以使用express.json()
与express.urlencoded()
就像在快车3.0。
This was differentstarting Express 4.0 to 4.15:
这与从Express 4.0 到 4.15 不同:
$ npm install --save body-parser
and then:
进而:
var bodyParser = require('body-parser')
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
The rest is like in Express 3.0:
其余的就像在Express 3.0 中一样:
Firstly you need to add some middleware to parse the post data of the body.
首先需要添加一些中间件来解析body的post数据。
Add one or both of the following lines of code:
添加以下一行或两行代码:
app.use(express.json()); // to support JSON-encoded bodies
app.use(express.urlencoded()); // to support URL-encoded bodies
Then, in your handler, use the req.body
object:
然后,在您的处理程序中,使用该req.body
对象:
// assuming POST: name=foo&color=red <-- URL encoding
//
// or POST: {"name":"foo","color":"red"} <-- JSON encoding
app.post('/test-page', function(req, res) {
var name = req.body.name,
color = req.body.color;
// ...
});
Note that the use of express.bodyParser()
is not recommended.
请注意,express.bodyParser()
不推荐使用。
app.use(express.bodyParser());
...is equivalent to:
...相当于:
app.use(express.json());
app.use(express.urlencoded());
app.use(express.multipart());
Security concerns exist with express.multipart()
, and so it is better to explicitly add support for the specific encoding type(s) you require. If you do need multipart encoding (to support uploading files for example) then you should read this.
存在安全问题express.multipart()
,因此最好明确添加对您需要的特定编码类型的支持。如果您确实需要多部分编码(例如支持上传文件),那么您应该阅读此.
回答by Sean Lynch
Security concern using express.bodyParser()
使用 express.bodyParser() 的安全问题
While all the other answers currently recommend using the express.bodyParser()
middleware, this is actually a wrapper around the express.json()
, express.urlencoded()
, and express.multipart()
middlewares (http://expressjs.com/api.html#bodyParser). The parsing of form request bodies is done by the express.urlencoded()
middleware and is all that you need to expose your form data on req.body
object.
而所有其他的答案目前推荐使用的express.bodyParser()
中间件,这其实是围绕着一个包装express.json()
,express.urlencoded()
和express.multipart()
中间件(http://expressjs.com/api.html#bodyParser)。表单请求正文的解析由express.urlencoded()
中间件完成,这就是您在req.body
对象上公开表单数据所需的全部内容。
Due to a security concernwith how express.multipart()
/connect.multipart()
creates temporary files for all uploaded files (and are not garbage collected), it is now recommendednot to use the express.bodyParser()
wrapper but instead use only the middlewares you need.
由于/如何为所有上传的文件创建临时文件(并且不是垃圾收集)的安全问题,现在建议不要使用包装器,而是仅使用您需要的中间件。express.multipart()
connect.multipart()
express.bodyParser()
Note: connect.bodyParser()
will soon be updated to only include urlencoded
and json
when Connect 3.0 is released (which Express extends).
注意:connect.bodyParser()
将很快更新为仅包含urlencoded
和json
发布 Connect 3.0 时(Express 扩展)。
So in short, instead of ...
简而言之,而不是...
app.use(express.bodyParser());
...you should use
...你应该使用
app.use(express.urlencoded());
app.use(express.json()); // if needed
and if/when you need to handle multipart forms (file uploads), use a third party library or middleware such as multiparty, busboy, dicer, etc.
如果/当您需要处理多部分表单(文件上传),请使用第三方库或中间件,例如 multiparty、busboy、dicer 等。
回答by yonran
Note: this answer is for Express 2. See herefor Express 3.
注意:此答案适用于 Express 2。请参阅此处了解 Express 3。
If you're using connect/express, you should use the bodyParser middleware: It's described in the Expressjs guide.
如果您使用 connect/express,则应使用bodyParser 中间件:Expressjs 指南中对此进行了描述。
// example using express.js:
var express = require('express')
, app = express.createServer();
app.use(express.bodyParser());
app.post('/', function(req, res){
var email = req.param('email', null); // second parameter is default
});
Here's the original connect-only version:
这是原始的仅连接版本:
// example using just connect
var connect = require('connect');
var url = require('url');
var qs = require('qs');
var server = connect(
connect.bodyParser(),
connect.router(function(app) {
app.post('/userlogin', function(req, res) {
// the bodyParser puts the parsed request in req.body.
var parsedUrl = qs.parse(url.parse(req.url).query);
var email = parsedUrl.email || req.body.email;;
});
})
);
Both the querystring and body are parsed using Rails-style parameter handling (qs
)rather than the low-level querystring
library. In order to parse repeated parameters with qs
, the parameter needs to have brackets: name[]=val1&name[]=val2
. It also supports nested maps. In addition to parsing HTML form submissions, the bodyParser can parse JSON requests automatically.
查询字符串和正文都使用Rails 风格的参数处理 ( qs
)而不是低级querystring
库来解析。为了用 解析重复的参数qs
,参数需要有括号:name[]=val1&name[]=val2
。它还支持嵌套映射。除了解析 HTML 表单提交之外,bodyParser 还可以自动解析 JSON 请求。
Edit: I read up on express.js and modified my answer to be more natural to users of Express.
编辑:我阅读了 express.js 并修改了我的答案,使其对 Express 用户更自然。
回答by med116
This will do it if you want to build the posted query without middleware:
如果您想在没有中间件的情况下构建已发布的查询,则可以这样做:
app.post("/register/",function(req,res){
var bodyStr = '';
req.on("data",function(chunk){
bodyStr += chunk.toString();
});
req.on("end",function(){
res.send(bodyStr);
});
});
That will send this to the browser
这会将其发送到浏览器
email=emailval&password1=pass1val&password2=pass2val
It's probably better to use middleware though so you don't have to write this over and over in each route.
不过最好使用中间件,这样您就不必在每条路线中一遍又一遍地编写它。
回答by mplewis
Note for Express 4 users:
Express 4 用户注意事项:
If you try and put app.use(express.bodyParser());
into your app, you'll get the following error when you try to start your Express server:
如果您尝试将其app.use(express.bodyParser());
放入您的应用程序,当您尝试启动 Express 服务器时,您将收到以下错误:
Error: Most middleware (like bodyParser) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.
错误:大多数中间件(如 bodyParser)不再与 Express 捆绑在一起,必须单独安装。请参阅https://github.com/senchalabs/connect#middleware。
You'll have to install the package body-parser
separately from npm, then use something like the following (example taken from the GitHub page):
您必须将软件包body-parser
与npm分开安装,然后使用如下所示的内容(示例取自GitHub 页面):
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser());
app.use(function (req, res, next) {
console.log(req.body) // populated!
next();
})
回答by David
Given some form:
给定某种形式:
<form action='/somepath' method='post'>
<input type='text' name='name'></input>
</form>
Using express
使用快递
app.post('/somepath', function(req, res) {
console.log(JSON.stringify(req.body));
console.log('req.body.name', req.body['name']);
});
Output:
输出:
{"name":"x","description":"x"}
req.param.name x
回答by lakesare
Backend:
后端:
import express from 'express';
import bodyParser from 'body-parser';
const app = express();
app.use(bodyParser.json()); // add a middleware (so that express can parse request.body's json)
app.post('/api/courses', (request, response) => {
response.json(request.body);
});
Frontend:
前端:
fetch("/api/courses", {
method: 'POST',
body: JSON.stringify({ hi: 'hello' }), // convert Js object to a string
headers: new Headers({ "Content-Type": "application/json" }) // add headers
});
回答by Chinthaka Senanayaka
app.use(express.bodyParser());
Then for app.post
request you can get post values via req.body.{post request variable}
.
然后对于app.post
请求,您可以通过req.body.{post request variable}
.
回答by yeelan
Update for Express 4.4.1
Express 4.4.1 更新
Middleware of the following is removed from Express.
从 Express 中删除了以下中间件。
- bodyParser
- json
- urlencoded
- multipart
- 正文解析器
- json
- 网址编码
- 多部分
When you use the middleware directly like you did in express 3.0. You will get the following error:
当您像在 express 3.0 中那样直接使用中间件时。您将收到以下错误:
Error: Most middleware (like urlencoded) is no longer bundled with Express and
must be installed separately.
In order to utilize those middleware, now you need to do npmfor each middleware separately.
为了利用这些中间件,现在你需要为每个中间件分别做npm。
Since bodyParser is marked as deprecated, so I recommend the following way using json, urlencode and multipart parser like formidable, connect-multiparty. (Multipart middleware is deprecated as well).
由于 bodyParser 被标记为已弃用,因此我建议使用以下方式使用 json、urlencode 和 multipart 解析器,如 formidable、connect-multiparty。(多部分中间件也已弃用)。
Also remember, just defining urlencode + json, the form data will not be parsed and req.body will be undefined. You need to define a middleware handle the multipart request.
还要记住,只是定义了 urlencode + json,表单数据不会被解析,req.body 不会被定义。您需要定义一个中间件来处理多部分请求。
var urlencode = require('urlencode');
var json = require('json-middleware');
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
app.use(json);
app.use(urlencode);
app.use('/url/that/accepts/form-data', multipartMiddleware);
回答by cwingrav
I was searching for this exact problem. I was following all the advice above but req.body was still returning an empty object {}. In my case, it was something just as simple as the html being incorrect.
我正在寻找这个确切的问题。我遵循了上面的所有建议,但 req.body 仍然返回一个空对象 {}。就我而言,这就像 html 不正确一样简单。
In your form's html, make sure you use the 'name'
attribute in your input tags, not just 'id'
. Otherwise, nothing is parsed.
在表单的 html 中,确保'name'
在输入标签中使用该属性,而不仅仅是'id'
. 否则,不会解析任何内容。
<input id='foo' type='text' value='1'/> // req = {}
<input id='foo' type='text' name='foo' value='1' /> // req = {foo:1}
My idiot mistake is your benefit.
我的白痴错误是你的好处。