创建调用远程 REST API 和 returns 结果的节点 REST API
Create Node REST API that calls remote REST API and returns results
我有一个本地 REST API,但我实际上只处理 POST。
mysite/api/ -> http://remoteSite.com/api/
所以当我的前端使用参数访问我的端点时,服务器会 post 那些到远程服务器(第 3 方 API)并且 return 结果到原始 POST.
我试过查看 Koa、Express、Axios、Bluebird,但似乎找不到合理的方法或合适的搜索词来查找示例。
您正在寻找 代理。
如果你必须使用 NodeJS,你可以查看 the node-http-proxy library:
var http = require('http'),
httpProxy = require('http-proxy');
//
// Create your proxy server and set the target in the options.
//
httpProxy.createProxyServer({target:'http://localhost:9000'}).listen(8000);
//
// Create your target server
//
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(9000);
在这里,localhost 端口 8000 充当 localhost 端口 9000 的代理。您想将其设置为指向远程服务器。
您还可以查看 Apache web server or Nginx 以寻找设置代理的替代方法,可能更省力且更稳定。
我有一个本地 REST API,但我实际上只处理 POST。
mysite/api/ -> http://remoteSite.com/api/
所以当我的前端使用参数访问我的端点时,服务器会 post 那些到远程服务器(第 3 方 API)并且 return 结果到原始 POST.
我试过查看 Koa、Express、Axios、Bluebird,但似乎找不到合理的方法或合适的搜索词来查找示例。
您正在寻找 代理。
如果你必须使用 NodeJS,你可以查看 the node-http-proxy library:
var http = require('http'),
httpProxy = require('http-proxy');
//
// Create your proxy server and set the target in the options.
//
httpProxy.createProxyServer({target:'http://localhost:9000'}).listen(8000);
//
// Create your target server
//
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(9000);
在这里,localhost 端口 8000 充当 localhost 端口 9000 的代理。您想将其设置为指向远程服务器。
您还可以查看 Apache web server or Nginx 以寻找设置代理的替代方法,可能更省力且更稳定。