Why won't my ExpressJS properly execute a request command?

给你一囗甜甜゛ 提交于 2020-01-06 19:33:49

问题


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

Shouldn't this translate to http://www.somesite.com/search?location=NYC&text=text&authID=[mykey]?


回答1:


You have quite a few mistakes in this code that make it pretty clear you need to review how asynchronous code flow works. You are calling makeRequest before it is defined, and you are attempting to return a value from your response callback in http.get, which will not work. You are also missing 'var' keywords all over.

The main issue I see beyond that is that you are passing your URL arguments in the request body, which will not work. Secondly, you are calling req.write and req.end after the request has already been ended inside http.get. And JSON.stringify is entirely the wrong way to generate URL parameters.

Here is a basic request method that will work

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


来源:https://stackoverflow.com/questions/7382757/why-wont-my-expressjs-properly-execute-a-request-command

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!