Node.js API获取从我的API到另一个API的请求?
我正在尝试创建一个后端,将GET请求发送到另一个API 例如: 我的API:Node.js API获取从我的API到另一个API的请求?,node.js,api,express,controller,routing,Node.js,Api,Express,Controller,Routing,我正在尝试创建一个后端,将GET请求发送到另一个API 例如: 我的API:localhost:3000/ 路由:/getdata/data1 其他API:API.com/target/data (这是一个伪造的URL,只需假设此路由包含我想要的数据) 如何从API向该API发送get请求Ajax.get?对于Node.js,使用 例如: var request = require('request'); request('http://www.google.com', function (er
localhost:3000/
路由:
/getdata/data1
其他API:
API.com/target/data
(这是一个伪造的URL,只需假设此路由包含我想要的数据)
如何从API向该API发送get请求Ajax.get
?对于Node.js,使用
例如:
var request = require('request');
request('http://www.google.com', function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
});
替换为您的URL。您需要查看是否需要使用其他API进行授权;否则您将获得HTTP 401。您可以使用节点中的内置模块,或使用第三方软件包,如
超文本传输协议
使用内置模块的示例,例如:
// The 'https' module can also be used
const http = require('http');
// Example route
app.get('/some/api/endpoint', (req, res) => {
http.get('http://someapi.com/api/endpoint', (resp) => {
let data = '';
// Concatinate each chunk of data
resp.on('data', (chunk) => {
data += chunk;
});
// Once the response has finished, do something with the result
resp.on('end', () => {
res.json(JSON.parse(data));
});
// If an error occured, return the error to the user
}).on("error", (err) => {
res.json("Error: " + err.message);
});
});
要求
或者,可以使用第三方软件包,例如
首次安装请求:
npm安装-s请求
然后将路线更改为如下所示:
const request = require('request');
// Example route
app.get('/some/api/endpoint', (req, res) => {
request('http://someapi.com/api/endpoint', (error, response, body) => {
if(error) {
// If there is an error, tell the user
res.send('An erorr occured')
}
// Otherwise do something with the API data and send a response
else {
res.send(body)
}
});
});
另一个API在同一个web应用程序中?不同。这是另一个网络应用。我基本上希望我的api请求其他api的数据,而来自我api的响应是=来自其他api的响应(json数据),可能是