nginx监听转发解决axios跨域问题
在前端部署过程中遇到了axios的跨域问题。 跨域问题可以后端解决,这里介绍前端解决的办法,(毕竟不帮忙配nginx的前端不是好前端嘛 嘿嘿)。 教程如下
1.windows安装nginx
https://nginx.org/en/download.html 我安装的是stable version下的nginx/Windows-1.18.0 PGP 安装后解压到软件工作区所在的文件夹
2.修改配置
我用的是vscode(其他编译软件也可以) 找到nginx-1.18.0 conf nginx.conf 打开后找到这个位置http{ include mime.types; default_type application/octet-stream; … } 此时已经有一个server{}在里面,不要动它,在它后面添加如下代码块。 千万不要放错位置!不要在文件中随便添加空格!
server{
listen 8000;
server_name localhost;
location /{
proxy_pass http://你需要部署的位置;
}
location /api{
proxy_pass http://接口的位置/api;
}
3.启动nginx
右击nginx-1.18.0,在集成终端中打开,输入./nginx或./nginx.exe。如果报错,可以尝试打开nginx文件夹,双击nginx.exe,不过不建议用这种方式,因为可能会在后台打开多个nginx。 这里报错的可能原因有:文件夹路径的命名用了中文或空格。建议尝试去解决报错问题。
nginx服务器就会被启动,此时打开网页localhost就会变成这样,这说明nginx已经启动成功了
这里介绍几个nginx命令
# 强制停止nginx服务器,如果有未处理的数据,丢弃 nginx -s stop # 优雅的停止nginx服务器,如果有未处理的数据,等待处理完成之后停止 nginx -s quit # 重载nginx nginx -s reload
4.axios请求
这里给出axios代码参考
var but=document.getElementById("id1");
but.onclick=function(){
axios({
method:POST,
url:http://localhost:8000/api/接口后缀,
data:{
.....
}
}).then(response=>{
console.log(response);
});
}
此时再打开localhost:8000就可以看到你部署的页面了
