使用koajs做一个代理跨域服务,可以代理任意网站和接口
使用koajs做一个代理跨域服务。
const Koa = require('koa');
const proxy = require('koa-proxy');
const Router = require('koa-router');
const session = require('koa-session');
const app = new Koa();
const router = new Router();
app.keys = ['secret']; // 用于加密会话 ID 的密钥
app.use(session(app));
/**
 * 代理网站
 */
router.all('/aa/:path(.*)', async (ctx, next) => {
  //后台自己添加请求头
  // ctx.request.headers.cookie = 'csrftoken=uC2GbKsmAX7aqQuLtrKN5htiYZ4P3z0eKx6KMYQlGJxqeOJelnWp9ORqHOyYXKPR; sessionid=5a50kpokgthu53c9g9bqqa3dxypi8qz9';
  // ctx.request.headers.Authorization = 'JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMjE0ZmRlMzMtYjlmNC00OGNkLTljODQtN2U2M2Y1M2IxZGM1IiwidXNlcm5hbWUiOiJhZG1pbiIsImV4cCI6ODgwNzkxNDI2NTAsImVtYWlsIjoiYWRtaW5AMTYzLmNvbSJ9.iERNw8S5g-YDGk_s0Y9taNozLiqSlrg2Cklsah3l6bs';
  await proxy({
    host: 'http://111.222.333.444',
    jar: true,
    map: function (path) {
      return path.replace('/aa', '');
    },
  })(ctx, next)
});
app.use(router.routes());
app.listen(3000);
console.log('Server running at http://localhost:3000/');
/*
使用方式:
原链接:
http://111.222.333.444/api/v1/user/
现请求方式:
fetch("http://localhost:3000/aa/api/v1/user/", {
  "headers": {
    "accept": "application/json",
    "accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
    "authorization": "JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiMjE0ZmRlMzMtYjlmNC00OGNkLTljODQtN2U2M2Y1M2IxZGM1IiwidXNlcm5hbWUiOiJhZG1pbiIsImV4cCI6ODgwNzkxNDI2NTAsImVtYWlsIjoiYWRtaW5AMTYzLmNvbSJ9.iERNw8S5g-YDGk_s0Y9taNozLiqSlrg2Cklsah3l6bs",
    "cache-control": "no-cache",
    "pragma": "no-cache"
  },
  "referrerPolicy": "strict-origin-when-cross-origin",
  "body": null,
  "method": "GET",
  "mode": "cors",
  "credentials": "include"
});
*/
使用方式看注释
博客园作者:herry菌朋友,看到这里,关注作者的公众号吧,不漏掉更新哦

 
   
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号