关于前端: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的形式,该怎么做呢?

接手的我的项目就没有配置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就能胜利设置

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理