nginx解决跨域

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

通常咱们的解决方法是在webpack中设置代理,配置devServer:nginx

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

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

因此,若是不是经过devServer的方式,该怎么作呢?api

image

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

那么如今的想法要让浏览器地址与接口地址同源,那么cookie天然可以设置成功了!浏览器

能够经过配置nginx来实现。cookie

配置:spa

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
  • 还有一步,在项目中,要动态配置接口地址:code

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

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

相关文章
相关标签/搜索