50行代码实现 node 转发 API 请求服务

GitHub地址:node-proxy-api

简单的几行代码实现如何通过Node + Express + superagent 转发 API 请求。已部署到 Heroku。

安装依赖

Node.js 转发请求用到了 expresssuperagent. superanget是一个 Node.js HTTP client。

npm i express superagent -S

端口设置

由于部署到Heroku时,端口是动态分配的,所以需要根据 process.env.NODE_ENV 动态设置端口:

app.set('port', (process.env.PORT || 5000));

定义接口

根据前端所需,定义了如下三个接口:

app.get('/movie/:type', function (req, res) {
  var sreq = request.get(HOST + req.originalUrl)
  sreq.pipe(res);
  sreq.on('end', function (error, res) {
    console.log('end');
  });
})

app.get('/movie/subject/:id', function (req, res) {
  var sreq = request.get(HOST + req.originalUrl)
  sreq.pipe(res);
  sreq.on('end', function (error, res) {
    console.log('end');
  });
})

app.get('/movie/search', function (req, res) {
  var sreq = request.get(HOST + req.originalUrl)
  sreq.pipe(res);
  sreq.on('end', function (error, res) {
    console.log('end');
  });
})

CORS设置

跨源资源共享 ( CORS )机制让Web应用服务器能支持跨站访问控制,从而使得安全地进行跨站数据传输成为可能。
主要是通过设置Access-Control-Allow-Origin: *

app.all('*', function (req, res, next) {
  if (!req.get('Origin')) return next();
  // use "*" here to accept any origin
  res.set('Access-Control-Allow-Origin', '*');
  res.set('Access-Control-Allow-Methods', 'GET');
  res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
  // res.set('Access-Control-Allow-Max-Age', 3600);
  if ('OPTIONS' == req.method) return res.send(200);
  next();
});

端口监听

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

启动

cd node-proxy
node index.js

具体见node-proxy/index.js

部署到Heroku

详情见 部署 Node.js 到 Heroku

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值