前端利用nginx代理解决跨域

前端怎么配置nginx解决跨域

下载nginx

https://nginx.org/en/download.html

根据自己电脑下载stable version稳定版本的nginx,然后解压

nginx -t  //  检查是否有语法错误
nginx     //  启动nginx,默认是80端口,或者双击nginx.exe也是一样的
前端怎么利用nginx解决开发环境下的跨域

前端项目跑在:http://localhost:8080

    axios.get("/api/testCors").then((res) => {
      console.log(res);
    });

提供资源的服务器:http://localhost:9000

const http = require("http");
const app = http.createServer((req, res) => {
  if (req.url === "/api/testCors") {
    res.end("i just wanna be cool");
  }
});

app.listen(9000, "localhost", () => {
  console.log("localhost:9000开启服务");
});

直接在项目中请求肯定会跨域

修改nginx配置:

nginx.cong文件

server {
    listen       8090;
    server_name  localhost;

    location / {
        proxy_pass http://localhost:8080;
    }

    location /api {
        proxy_pass http://localhost:9000;
    }
}

修改之后,记得重启nginx

nginx开启了一个服务,跑在了http://localhost:9000

通过访问这个地址,就可以访问正确的页面了

它是怎么解决跨域的呢?

通过访问http://localhost:8090,将 “/” 路径代理到了 http://localhost:8080,我们就可以看到前端页面了 ;调用接口 “/api/testCors” 自动拼接了 “http://localhost:9000”,与浏览器url地址一致并没有跨域,不会报跨域的错误,只不过“http://localhost:8090/api/testCors”是找不到这个资源的,我们通过代理将他代理到了“http://localhost:9000/api/testCors”,就能请求到资源了,这是服务器请求服务器,自然也没有跨域问题

​ -----------------------------------------

​ | 请求路径为/,代理到8080端口

​ | /

请求 -> | 8090

​ | \

​ | 请求路径为/api,代理到9000端口

​ ---------------------------------------

localhost:8090/index.html,代理到localhost:8080/index.html

localhost:8090/api/testCors,代理到localhost:9000/api/login

nginx的主要作用

负载均衡

反向代理

正向代理

正向代理客户端,反向代理服务器

动静分离

将静态资源如css,js,图片,动图等放入Nginx,让Nginx渲染资源

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值