[英]Is there a simple way to send POST request using Node.js?
我需要将某些status=1
数据发送到另一台服务器上的PHP文件,该服务器将更新数据库中的一行。
这似乎是这样的:
var data = {
var1:"something",
var2:"something else"
};
var querystring = require("querystring");
var qs = querystring.stringify(data);
var qslength = qs.length;
var options = {
hostname: "example.com",
port: 80,
path: "some.php",
method: 'POST',
headers:{
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': qslength
}
};
var buffer = "";
var req = http.request(options, function(res) {
res.on('data', function (chunk) {
buffer+=chunk;
});
res.on('end', function() {
console.log(buffer);
});
});
req.write(qs);
req.end();
我必须发送一个简单的“ 1”,所以必须有更好的方法。 我已经阅读了有关节点“请求”库的信息,但是我不想为此任务安装另一个扩展。
but honestly for this task I would rather not instal a whole nother extension.
节点标准库被设计为低级的,不要害怕安装将低级的东西抽象出来的模块。 您找到的大多数节点应用程序将包含许多小型实用程序模块。
如果您对request
的复杂性感到恐惧,那么您可能想检查一下get ,它是一个类似于请求的简约HTTP库。
使用针 ,使用以下方法npm install needle
: npm install needle
。
一个简单的帖子可以这样执行:
var needle = require('needle');
var options = {
headers: { 'Content-Type': 'application/x-www-form-urlencoded'}
}
needle.post('http://example.com/some.php', 'status=1', options, function(err, resp) {
//...
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.