[英]Add parameters to HTTP POST request in Node.JS
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
请求的正文中嵌入参数以及如何从接收器模块中捕获它们。
Would you mind using the request library . 您介意使用请求库吗? Sending a post request becomes as simple as 发送帖子请求变得如此简单
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. 请求库在request.post
方法中也有一个用于发布的快捷方式,您可以在其中传递URL来进行发布请求,并发送数据到该URL。
Edit based on comment 根据评论进行编辑
To "capture" a post request it would be best if you used some kind of framework. 要“捕获”发布请求,最好使用某种框架。 Since express is 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 guide by the author himself. 如果您不熟悉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 您需要做的就是创建一个发布路由,回调函数将包含发布到该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
});
If you want to use the native http
module, parameters can be included in body this way:如果你想使用原生的http
模块,参数可以这样包含在 body 中:
var http = require('follow-redirects').http;
var fs = require('fs');
var options = {
'method': 'POST',
'hostname': 'example.com',
'path': '/foo.html',
'headers': {
},
'maxRedirects': 20
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function (chunk) {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
res.on("error", function (error) {
console.error(error);
});
});
var postData = "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"examplekey\"\r\n\r\nexamplevalue\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--";
req.setHeader('content-type', 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW');
req.write(postData);
req.end();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.