2011-09-12 33 views
0
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]为什么我的ExpressJS不能正确执行请求命令?

+0

它看起来就像你试图做一个GET,但书面方式对邮件正文中的基本要求的方法。 –

回答

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); 
}); 
相关问题