通过 POST 请求从 node.js 服务器向 node.js 服务器发送数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9768192/
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
Sending data through POST request from a node.js server to a node.js server
提问by Masiar
I'm trying to send data through a POSTrequest from a node.js server to another node.js server. What I do in the "client" node.js is the following:
我正在尝试通过POST来自 node.js 服务器的请求将数据发送到另一个 node.js 服务器。我在“客户端”node.js 中所做的如下:
var options = {
host: 'my.url',
port: 80,
path: '/login',
method: 'POST'
};
var req = http.request(options, function(res){
console.log('status: ' + res.statusCode);
console.log('headers: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function(chunk){
console.log("body: " + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
This chunk is taken more or less from the node.js website so it should be correct. The only thing I don't see is how to include username and password in the optionsvariable to actually login. This is how I deal with the data in the server node.js (I use express):
这个块或多或少来自 node.js 网站,所以它应该是正确的。我唯一没有看到的是如何在options变量中包含用户名和密码以实际登录。这是我处理服务器 node.js 中数据的方式(我使用 express):
app.post('/login', function(req, res){
var user = {};
user.username = req.body.username;
user.password = req.body.password;
...
});
How can I add those usernameand passwordfields to the optionsvariable to have it logged in?
如何将这些username和password字段添加到options变量以使其登录?
Thanks
谢谢
回答by Tomalak
Posting data is a matter of sending a query string (just like the way you would send it with an URL after the ?) as the request body.
发布数据是发送一个查询字符串(就像您在 之后使用 URL 发送它的方式一样?)作为请求正文的问题。
This requires Content-Typeand Content-Lengthheaders, so the receiving server knows how to interpret the incoming data. (*)
这需要Content-Type和Content-Length标头,因此接收服务器知道如何解释传入的数据。(*)
var querystring = require('querystring');
var http = require('http');
var data = querystring.stringify({
username: yourUsernameValue,
password: yourPasswordValue
});
var options = {
host: 'my.url',
port: 80,
path: '/login',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data)
}
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("body: " + chunk);
});
});
req.write(data);
req.end();
(*)Sending data requires the Content-Type header to be set correctly, i.e. application/x-www-form-urlencodedfor the traditional format that a standard HTML form would use.
(*)发送数据需要正确设置 Content-Type 标头,即application/x-www-form-urlencoded标准 HTML 表单将使用的传统格式。
It's easy to send JSON (application/json) in exactly the same manner; just JSON.stringify()the data beforehand.
application/json以完全相同的方式发送 JSON ( )很容易;只是JSON.stringify()事先的数据。
URL-encoded data supports one level of structure (i.e. key and value). JSON is useful when it comes to exchanging data that has a nested structure.
URL 编码的数据支持一级结构(即键和值)。在交换具有嵌套结构的数据时,JSON 很有用。
The bottom line is: The server must be able to interpret the content type in question. It could be text/plainor anything else; there is no need to convert data if the receiving server understands it as it is.
底线是:服务器必须能够解释有问题的内容类型。它可以是text/plain或其他任何东西;如果接收服务器按原样理解数据,则无需转换数据。
Add a charset parameter (e.g. application/json; charset=Windows-1252) if your data is in an unusual character set, i.e. not UTF-8. This can be necessary if you read it from a file, for example.
application/json; charset=Windows-1252如果您的数据使用不寻常的字符集,即不是 UTF-8,请添加字符集参数(例如)。例如,如果您从文件中读取它,这可能是必要的。
回答by ranm8
You can also use Requestify, a really cool and very simple HTTP client I wrote for nodeJS + it supports caching.
您还可以使用Requestify,这是我为 nodeJS 编写的一个非常酷且非常简单的 HTTP 客户端,它支持缓存。
Just do the following for executing a POST request:
只需执行以下操作即可执行 POST 请求:
var requestify = require('requestify');
requestify.post('http://example.com', {
hello: 'world'
})
.then(function(response) {
// Get the response body (JSON parsed or jQuery object for XMLs)
response.getBody();
});

