我正在通过REST API执行POST操作,该API返回JSON数据。我正在尝试使用Node JS进行调用,但我没有得到任何响应。有人可以帮我找到这里的问题吗?
'use strict';
const request = require('request');
const snapOpts = {
url: 'https://triageqa.paypalcorp.com:8443/v1/triage/fetchers',
method: 'POST',
strictSSL: false
};
const snapFilter = {
"reporter": "sdmariappan",
"fetchers_list": {
"change_ticket_fetcher_request" : {
"start_time": "2018-01-01T00:00:00.000Z",
"end_time": "2018-02-07T00:00:00.000Z",
"pools" : [
"xxx"
]
}
}
};
let obj;
module.exports = function (router) {
router.get('/snap', function (req, res) {
callsnap(function (data) {
res.send(data)
});
});
};
function callsnap(cb) {
requestSnap("POST", snapFilter)
.then(data => {
obj = JSON.parse(JSON.stringify(data,null,2));
cb(obj);
})
.catch(err => {
console.error(err);
});
}
function requestSnap(method, queryData) {
snapOpts.method = method;
snapOpts.qs = queryData;
return new Promise((resolve, reject) => {
let responseData = '';
request(snapOpts)
.on('error', err => reject(err))
.on('data', chunk => responseData += chunk)
.on('end', () => resolve(responseData));
});
}
调用REST API的Curl命令:
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'Authorization: Bearer EEwJ6tF9x5' -d ' {
"reporter": "sdmariappan",
"fetchers_list": {
"change_ticket_fetcher_request" : {
"start_time": "2018-01-01T00:00:00.000Z",
"end_time": "2018-02-07T00:00:00.000Z",
"pools" : [
"xxx",
]
}
}
}
} ' 'https://triageqa.paypalcorp.com:8443/v1/triage/fetchers'
答案 0 :(得分:3)
我做了一些修改。
module.exports = function (router) {
router.get('/snap', function (req, res) {
requestSnap("POST", snapFilter)
.then(data => {
res.json(data);
})
.catch(err => {
res.status(400).json(data);
});
});
};
function requestSnap(method, queryData) {
snapOpts.method = method;
snapOpts.body = queryData;
return new Promise((resolve, reject) => {
request(snapOpts, function (err, res, body) {
if (err) {
console.error('error posting json: ', err)
reject(err);
}
console.log('body: ', body);
resolve(body);
})
});
}
答案 1 :(得分:1)
非常感谢Rahul。
在标题中添加内容类型后,我可以看到响应。不能正确看待我是错误的:(
const snapOpts = {
url: 'https://triageqa.paypalcorp.com:8443/v1/triage/fetchers',
method: 'POST',
json: true,
rejectUnauthorized: false,
headers: {
'Content-Type': 'application/json'
}
};