使用http进行POST

时间:2018-11-06 04:39:28

标签: node.js http post keep-alive

我确定这是一个简单的解决方案,但是我还没有弄清楚。在Python中,我们有一个很好的库来处理http请求requests。现在使用起来非常简单,我编写了一个简单的程序来测试概念:

import requests
s = requests.Session()
r = s.post('website.com',data={login details here})
r = s.post('website.com/something',data={other details})

这很好用,可以完成我想做的所有事情,但是不幸的是,这并不是我最初开发我想要的应用程序所用的语言。

现在,在node.js中,简单的POST请求当然不是太困难,但要困难一点,我不知道如何keep-alive进行第二次连接。使用下面的代码,我可以获得一个连接:

var options {
  options here, just know that I sent the keep-alive header
}
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 (body) {
    console.log('Body: ' + body);
  });
 });
 req.on('error', function(e) {
   console.log('problem with request: ' + e.message);
 });
 req.write();
 req.end();
}

好的,这很好,只是我不知道该如何使用保持活动状态并发送第二个请求。我认为我应该使用socket,但我对文档不完全理解,因为它们对我造成极大的困扰。通过互联网搜索时,我似乎找不到使用POST保持活动连接的人,或者实际上找不到任何使用两次的人。我真的很希望在一个keep-alive连接上使用两个不同的选项/数据的示例。

3 个答案:

答案 0 :(得分:1)

如果要使用SELECT `Org_ID`,`Org_Name`, `Org_Address`, `Org_Address2`, `Org_City`, `Org_State`, `Org_Zip`, `Org_County`, `Org_Website`, `Org_Phone`, `Org_fax`, `Org_Email` FROM `organization` 核心模块,则应使用http来设置agent

keep-alive

然后使用var myAgent = new http.Agent({ keepAlive: true, maxSockets: 1, keepAliveMsecs: 3000 }) 模块并将其设置为option的代理属性,例如波纹管片段

request

用于设置响应车中的第二个请求Cookie标头,其读为this

答案 1 :(得分:0)

无需使用其他库(例如请求)。

相反,像这样实例化一个新的http.agent对象。

const keepAliveAgent = new http.Agent({ keepAlive: true });

然后将其包含在您的http请求选项对象中,就像这样...

const requestOptions = {
  agent: keepAliveAgent,
  headers: {
    Connection: 'keep-alive'
  }
  // the rest of your options...
}

const request = https.request(requestOptions, (response) => {
  // handle response here
});

request.write("your request body here"); // if you need to POST/PUT data
request.end();

答案 2 :(得分:0)

modular AWS SDK for JavaScript 的 AWS 开发工具包中的 JavaScript v3 默认启用 HTTP 保持连接