我正在尝试在Node.js中进行GET REST调用。当我使用postman执行GET时,我得到了一个正确的JSON输出,但是在node.js代码中,我得到了一些特殊字符形式的输出。
我的GET代码如下所示:
var http = require('http');
var requestrespone = require("request");
var config = require('../config/config.js');
var jsonFile = require('jsonfile');
var jsonFile=require('../json_input/jsoninput.json');
var cheerio =require('cheerio');
var express=require('express');
var getOptions=
{
host : config.host,
method : config.get,
path: config.getpath,
headers :config.getheader
};
console.info('Options prepared:');
console.info(getOptions);
console.info('Do the GET call');
var reqGet = http.request(getOptions, function(res) {
console.log("statusCode: ", res.statusCode);
// uncomment it for header details
// console.log("headers: ", res.headers);
res.on('data', function(d) {
console.info('GET result after GET:\n');
console.log(d);
console.info('\n\nCall completed');
});
});
reqGet.end();
reqGet.on('error', function(e) {
console.error(e);
});
我的输出如下:
<Buffer 1f 8b 08 00 00 00 00 00 00 00 54 91 41 4f e3 30 10 85 ff 8b cf a6 38 89
13 db bd 22 a8 2a b1 a5 6a 17 71 40 3d 4c e2 69 e5 25 b5 8d eb 14 15 c4 7f df ..
. >
请告诉我,我做错了什么?
答案 0 :(得分:1)
将其转换为字符串。您获得Buffer
类型。
假设data
是您的结果并且Buffer
类型
data.toString();
答案 1 :(得分:0)
我总是发现使用superagent通过节点程序进行POST / GET调用的最佳方法。回调也非常简单和可配置。
var request = require('superagent');
var config = require('./appConfig.json');
var dataToSend = {
authentication: 'any_auth_if_required',
data: 'data_to_post'
};
makePostCall(dataToSend);
makeGetCall(dataToSend);
function makePostCall(dataToSend){
request.post('URL_FOR_POST_CALL')
.send(dataToSend)
.set('Cross-Domain', 'true')
.set('Cache', 'false')
.accept('json')
.end(function(err, res) {
if (res && res.body) {
console.log(res.body);
//process.exit();
}
if(err){
console.log(err);
}
});
}
function makeGetCall(dataToSend){
request.get('URL_FOR_GET_CALL')
.query(dataToSend)
.set('Cross-Domain', 'true')
.set('Cache', 'false')
.accept('json')
.end(function(err, res) {
if (res && res.body) {
console.log(res.body);
//process.exit();
}
if(err){
console.log(err);
}
});
}
答案 2 :(得分:0)
而是Native Node.js方法:
var options = {
"method": "GET",
"hostname": "localhost",
"port": "80",
"path": "/api/data/",
"headers": {
"content-type": "application/json",
"cache-control": "no-cache"
}
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.write(JSON.stringify({ name: 'testName1', info: 'testInfoData' }));
req.end();
使用热门Request
资料库:
var request = require("request");
var options = { method: 'GET',
url: 'http://localhost:9000/api/things',
headers:
{ 'cache-control': 'no-cache',
'content-type': 'application/json' },
body: { name: 'testName1', info: 'testInfoData' },
json: true };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});