V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
huyu
V2EX  ›  问与答

如何解决跨域问题?

  •  
  •   huyu · Mar 25, 2021 · 1535 views
    This topic created in 1871 days ago, the information mentioned may be changed or developed.

    我使用 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
    })
    
    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3305 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 10:46 · PVG 18:46 · LAX 03:46 · JFK 06:46
    ♥ Do have faith in what you're doing.