nginx解决跨域

在项目开发中,我们很常见的一个问题是,本地是localhost开发的,接口一般是给IP地址,例如http://192.168.13.14/api, 这样直接在项目中调用接口 浏览器会报跨域错误, 因为localhosthttp://192.168.13.14并不是同源的。

一般我们的解决方法是在webpack中设置代理,配置devServer:

module.exports = {
    devServer: {
        proxy: {
            '/api': {
                target: 'http://192.168.13.14/api',
                changeOrigin : true
            }
        }
    }
}

设置以后,在接口访问 假设为http://localhost:8080/api时,会转发到http://192.168.13.14/api去.

所以,如果不是通过devServer的方式,该怎么做呢?

nginx解决跨域_第1张图片

接手的项目就没有配置webpack devServer,仔细看是设置了Access-Control-Allow-Origin: http://localhost:8054来解决接口跨域的,但是,这个项目的鉴权方式是cookie, 这里地址http://localhost:8054和接口地址==不同源导致cookie设置失败==

那么现在的想法要让浏览器地址与接口地址同源,那么cookie自然能够设置成功了!

可以通过配置nginx来实现。

配置:

server {
    listen 8055 {
        // 步骤1 
        location / {
            proxy_pass: http://localhost:8054/;
        }
        // 步骤2
        location /api {
            proxy_pass: http://192.169.13.14;
        }
    }
}

我访问的地址本来是http://localhost:8054, 这里我监听8055端口。

  • 步骤1 做地址的代理,当访问http://localhost:8055时,会映射到http://localhost:8054
  • 步骤2 做接口的代理,当访问http://localhost:8055/api/xxxx时,会映射到http://192.169.13.14/api/xxxx
  • 还有一步,在项目中,要动态配置接口地址:

    const apiAddress = window.location.protocol + '//' + window.location.host + '/api';

这样,浏览器地址与接口地址就都是localhost:8055开头的,不存在跨域的问题,cookie就能成功设置

你可能感兴趣的:(前端nginx)