前端怎么配置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渲染资源