【问题标题】:Why won't my ExpressJS properly execute a request command?为什么我的 ExpressJS 不能正确执行请求命令?
【发布时间】:2011-09-12 11:09:06
【问题描述】:
  searchJSON = {
    location: 'NYC',
    text: text,
    authID: apiKey
  };
  searchRequest = {
    host: siteUrl,
    port: 80,
    path: '/search',
    method: 'GET'
  };
searchResponse = makeRequest(searchRequest, searchJSON);
makeRequest = function(options, data) {
  var req;
  if (typeof data !== 'string') {
    data = JSON.stringify(data);
  }
  req = http.get(options, function(res) {
    var body;
    body = '';
    res.on('data', function(chunk) {
      body += chunk;
    });
    return res.on('end', function() {
      console.log(body);
    });
  });
  console.log(data);
  req.write(data);
  req.end();
};

这不应该翻译成http://www.somesite.com/search?location=NYC&text=text&authID=[mykey]吗?

【问题讨论】:

  • 看起来您正在尝试执行 GET,但正在写入消息正文。

标签: node.js express


【解决方案1】:

您在这段代码中有很多错误,很明显您需要查看异步代码流的工作原理。您在定义之前调用 makeRequest,并且您试图从 http.get 中的响应回调返回一个值,这将不起作用。您还完全缺少“var”关键字。

除此之外,我看到的主要问题是您在请求正文中传递了 URL 参数,这是行不通的。其次,在 http.get 中的请求已经结束之后,您正在调用 req.write 和 req.end。而 JSON.stringify 是完全错误的生成 URL 参数的方式。

这是一个可以使用的基本请求方法

var url = require('url');
var http = require('http');

function makeRequest(host, path, args, cb) {

  var options = {
    host: host,
    port: 80,
    path: url.format({ pathname: path, query: args})
  };

  http.get(options, function(res) {
    var body = '';

    res.on('data', function(chunk) {
      body += chunk;
    });

    res.on('end', function() {
      cb(body);
    });
  });
};


var searchJSON = {
  location: 'NYC',
  text: "text",
  authID: "apiKey"
};

makeRequest('somesite.com', '/', searchJSON, function(data) {
  console.log(data);
});

【讨论】:

    猜你喜欢
    • 2013-08-27
    • 2020-06-17
    • 1970-01-01
    • 2014-05-15
    • 1970-01-01
    • 2018-03-26
    • 1970-01-01
    • 2016-06-28
    相关资源
    最近更新 更多