V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
huyu
V2EX  ›  问与答

如何解决跨域问题?

  •  
  •   huyu · 2021-03-25 16:24:44 +08:00 · 668 次点击
    这是一个创建于 1099 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我使用 koa 代理几个第三方的接口,有几个都成功了,但是有一个死活就是返回 403 Invalid CORS request,浏览器没有跨域的错误,求大佬指导以下,下面是我的代码:

    const Koa = require('koa');
    const {createProxyMiddleware} = require('http-proxy-middleware');
    const app = new Koa();
    const cors = require('koa2-cors'); // 解决本地端口不一致的跨域
    
    app.use(cors({
      credentials: true,
      origin: 'http://127.0.0.1:8080',
      maxAge: 2592000,
      allowHeaders: '*'
    }));
    
    app.use(async (ctx, next) => {
    if (ctx.url.startsWith('/config')) {
        ctx.respond = false;
        ctx.body = createProxyMiddleware({
          target: 'https://pc-api.yun.cn',
          changeOrigin: true,
          secure: false,
          pathRewrite: {
            "^/config": ""
          },
          cookieDomainRewrite: {
            '.yun.cn': '127.0.0.1',
          }
        })(ctx.req, ctx.res, next)
    })
    
    /* 代理配置 end */
    const hostName = '127.0.0.1'; //本地 IP
    const port = 5000; //端口
    app.listen(port, hostName, () => {
      console.log(`服务运行在 http://${hostName}:${port}`);
    });
    
    // 前端
    const service = axios.create({
      timeout: 5000,
      withCredentials: true
    })
    
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5721 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 06:09 · PVG 14:09 · LAX 23:09 · JFK 02:09
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.