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&auth开发者_如何学PythonID=[mykey]
?
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);
});
精彩评论