简体   繁体   English

是否有使用Node.js发送POST请求的简单方法?

[英]Is there a simple way to send POST request using Node.js?

I need to send some data, status=1 , to a PHP file on another server that will update a row in a database. 我需要将某些status=1数据发送到另一台服务器上的PHP文件,该服务器将更新数据库中的一行。

This is what seems to be the way: 这似乎是这样的:

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();

I have to send a simple '1' so there has to be a better way. 我必须发送一个简单的“ 1”,所以必须有更好的方法。 I have read about the node 'request' library, but I'd prefer not to install another extension for this task. 我已经阅读了有关节点“请求”库的信息,但是我不想为此任务安装另一个扩展。

but honestly for this task I would rather not instal a whole nother extension.

The node standard library is designed to be low level, don't be afraid to install modules that abstract the low level stuff away. 节点标准库被设计为低级的,不要害怕安装将低级的东西抽象出来的模块。 Most node applications you find will contain loads of small utility modules. 您找到的大多数节点应用程序将包含许多小型实用程序模块。

If you are daunted by the complexity of request you might want to check out got which is a minimalistic http library just like request. 如果您对request的复杂性感到恐惧,那么您​​可能想检查一下get ,它是一个类似于请求的简约HTTP库。

Use needle , install it using: npm install needle . 使用 ,使用以下方法npm install needlenpm install needle

A simple Post can be performed like this: 一个简单的帖子可以这样执行:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM