1

您好我正在尝试在 Node.js 中向此 Post 请求添加查询。我不知道该怎么做。这是我正在使用的 Post 请求代码,

    var options = {
  host: 'ws.ispeech.org',
  port: 80,
  path: '/api/rest/1.5',
  method: 'POST',
};

var http = require('http');
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();
4

1 回答 1

3

查询字符串是 URL 的一部分,node.js 选项对象将其称为“路径” 。因此,您可以简单地将查询字符串添加到路径中:

var query = 'foo=bar&abc=123';
var options = {
  host: 'ws.ispeech.org',
  port: 80,
  path: '/api/rest/1.5' + '?' + query,
  method: 'POST',
};

请注意,还有一个“查询字符串”模块将为您编码对象属性/值:

var query = querystring.stringify({foo:'bar', abc:123});
// query => "foo=bar&abc=123"
于 2012-07-27T15:18:09.557 回答