[英]REST API integration to 3rd party
I'm trying to create REST API. 我正在尝试创建REST API。 My API should return a list of users taken from a 3rd party (after some manipulations) and return it.
我的API应该返回从第三方获取的用户列表(经过一些操作)并返回。
Here is my code: 这是我的代码:
function getUsersFrom3rdParty(options) {
https.get(options, (resp) => {
let data ='';
// A chunk of data has been received.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
console.log(JSON.parse(data));
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
}
exports.getUsers = (req, res, next) => {
var data = getUsersFrom3rdParty();
//do the manilupations and return to the api
};
I don't get the data in getUsers
function. 我没有在
getUsers
函数中获取数据。
I'd suggest using something like axios
- npmjs - for making asynchronous calls to a 3rd party API: 我建议使用
axios
- npmjs之类的东西来异步调用第三方API:
const axios = require('axios')
function getUsersFrom3rdParty(options) {
const processResponse = (response) => {
const processedResponse = ...
// do whatever you need to do, then return
return processedResponse
}
return axios.get('/example.com')
.then(processResponse)
}
// then, you can use `getUsersFrom3rdParty` as a promise
exports.getUsers = (req, res, next) => {
const handleResponse = (data) => {
res.json({ data }) // or whatever you need to do
}
const handleError = (err) => {
res.json({ error: 'Something went wrong!' }) // or whatever you need to do
}
getUsersFrom3rdParty(...)
.then(handleResponse)
.catch(handleError)
}
This way, you're waiting for your API call to finish before you render something and/or return a response. 这样,您正在等待API调用完成,然后再渲染某些内容和/或返回响应。
You are not passing options variable when you are calling getUsersFrom3rdParty function 调用getUsersFrom3rdParty函数时,您没有传递options变量
var data = getUsersFrom3rdParty(options);
You have to pass options to make it work and I suggest to use request module .It works better than https module. 您必须传递选项以使其正常工作,我建议使用request模块。它比https模块更好。
Here is your code using request 这是您使用请求的代码
const request = require("request");
function getUsersFrom3rdParty(options) {
request(options, (error, response, body) => {
if (!error && response.statusCode == 200) {
//Returned data
console.log(JSON.parse(body));
}
});
}
exports.getUsers = (req, res, next) => {
var data = getUsersFrom3rdParty(options);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.