javascript 向 Node.JS 中的 HTTP POST 请求添加参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22223868/
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
Add parameters to HTTP POST request in Node.JS
提问by Sameh Kamal
I've known the way to send a simple HTTP request using Node.js as the following:
我知道使用 Node.js 发送简单 HTTP 请求的方法如下:
var http = require('http');
var options = {
host: 'example.com',
port: 80,
path: '/foo.html'
};
http.get(options, function(resp){
resp.on('data', function(chunk){
//do something with chunk
});
}).on("error", function(e){
console.log("Got error: " + e.message);
});
I want to know how to embed parameters in the body of POST
request and how to capture them from the receiver module.
我想知道如何在POST
请求正文中嵌入参数以及如何从接收器模块中捕获它们。
回答by Akshat Jiwan Sharma
Would you mind using the request library. Sending a post request becomes as simple as
你介意使用请求库。发送 post 请求变得如此简单
var options = {
url: 'https://someurl.com',
'method': 'POST',
'body': {"key":"val"}
};
request(options,function(error,response,body){
//do what you want with this callback functon
});
The request library also has a shortcut for post in request.post
method in which you pass the url to make a post request to along with the data to send to that url.
请求库还有一个 post inrequest.post
方法的快捷方式,您可以在其中传递 url 以发出 post 请求以及要发送到该 url 的数据。
Edit based on comment
根据评论编辑
To "capture" a post request it would be best if you used some kind of framework. Since expressis the most popular one I will give an example of express. In case you are not familiar with express I suggest reading a getting started guideby the author himself.
要“捕获”发布请求,最好使用某种框架。由于express是最受欢迎的,我将举一个 express 的例子。如果您不熟悉 express,我建议您阅读作者本人的入门指南。
All you need to do is create a post route and the callback function will contain the data that is posted to that url
您需要做的就是创建一个 post 路由,回调函数将包含发布到该 url 的数据
app.post('/name-of-route',function(req,res){
console.log(req.body);
//req.body contains the post data that you posted to the url
});