vue项目打包完成之后,直接打开html文件,会出现以下报错:
原因
- 在浏览器打开本地的html文件, 上面请求的模型资源文件是一个本地文件, 协议是file://,如果是在服务器启动的话,则使用的是http或者https协议。
出于安全性考虑, Chrome默认禁止了这种用法,file协议和http/https协议不同,会被Chrome认为是跨域访问,所以会报被CORS(Cross-Origin Resource Sharing,跨域资源共享)的安全策略阻止。
所以才会导致我的页面一直处于加载的状态 - 这个问题只会发生在本地,如果是部署到服务器上面,或者是自己在vscode里面通过插件Live Server打开,都是没有问题的
解决跨域 —————Nginx
- 1.nginx下载
http://nginx.org/en/download.html -
2.解压下载的nginx,解压之后文件目录如下
- 3.npm run build打包项目,会生成一个dist文件夹
-
4.将dist文件夹拖到上面解压出来的文件夹中的html文件中
- 5.配置
- 解压出来的文件中 conf=>nginx.conf
- 如果配置多个项目 就再加server对象
server {
listen 8080;//监听的端口,项目运行的接口,前后端接口都被代理到这个接口
server_name localhost; //项目运行地址的域名 IPv4地址
autoindex on;//是否跨域
#charset koi8-r;
#access_log logs/host.access.log main;
#当路径匹配到/时,将会打开配置好的静态资源页面
location / {
root html/dist; //配置要打开的资源的根目录的地址,是以 nginx 下的 html 文件夹中dist为根目录来查找的
index index.html index.htm;
try_files $uri $uri/ /index.html;//解决跳转之后刷新404问题
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# 配置反向代理,解决跨域问题
#当路径匹配到/api时,将用http://localhost:3000来代替
location /api {
rewrite ^/api/(.*)$ /$1 break;
proxy_pass http://localhost:3000;//要代理的后端接口地址
}
}
- 6.启动nginx服务器
- 常用命令
- start nginx 开机
- nginx -s stop 快速关机
- nginx -s quit 优雅关机
- nginx -s reload 重新加载配置文件
- nginx -s reopen 重新打开日志文件
- 常用命令
- 7.打开浏览器,输入配置时设置的运行地址,访问项目
localhost:8080
记录跨域过程中的问题
- 代理失败 后端接口一直报404
- 首次进入成功,刷新之后一直是欢迎界面
- 解决办法:
成功杀掉进程就关闭了,也访问不到欢迎界面了,之后再重启再reload就能代理到了taskkill /f /t /im nginx.exe
- 解决办法: