vue+nginx解决跨域问题遇到的坑No 'Access-Control-Allow-Origin' header is present on the requested resource.
1.在vue config文件夹下index.js设置项目启动地址
我这里设置的就是localhost:8899访问项目
2.在vue config文件夹下dev.env.js配置nginx地址
'use strict' const merge = require('webpack-merge') const prodEnv = require('./prod.env') module.exports = merge(prodEnv, { NODE_ENV: '"development"', //BASE_API: '"https://easy-mock.com/mock/5950a2419adc231f356a6636/vue-admin"', BASE_API: '"http://localhost:9001"', //这个是nigin的地址,使用nigin解决跨域问题 })
3. 配置nginx
server { listen 9001; server_name localhost; location /eduservice/ { proxy_pass http://localhost:8001/eduservice/; } location /eduoss/ { proxy_pass http://localhost:8002/; } location /vod/ { proxy_pass http://localhost:8003/; } }
这个项目访问的逻辑 客户端localhost:8899 去访问nginx localhost:9001,nginx通过请求路径代理到不同的后端服务器。但是在实现中发现会出现Access-Control-Allow-Origin' header is present on the requested resource错误
原因是nginx 默认是不能通过跨域的方式访问的及 localhost:8899 到nignx localhost:9001存在一个跨域
需要给Nginx服务器配置响应的header参数:
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
1. Access-Control-Allow-Origin
nginx默认是不被允许跨域的。给Nginx服务器配置`Access-Control-Allow-Origin *`后,表示服务器可以接受所有的请求源(Origin),即接受所有跨域的请求。
2. Access-Control-Allow-Headers 是为了防止出现以下错误:
Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
这个错误表示当前请求Content-Type的值不被支持。其实是我们发起了"application/json"的类型请求导致的。这里涉及到一个概念:预检请求(preflight request)
,请看下面"预检请求"的介绍。
3. Access-Control-Allow-Methods 是为了防止出现以下错误:
Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
所以当出现Access-Control-Allow-Origin' header is present on the requested resource.只需要修改nginx配置 加上
add_header 'Access-Control-Allow-Origin' '*';就可以结局问题了
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
gzip on;
client_max_body_size 1024m;
proxy_connect_timeout 600;
proxy_read_timeout 600;
proxy_send_timeout 600;
add_header 'Access-Control-Allow-Origin' '*';
server {
listen 9001;
server_name localhost;
location /eduservice/ {
proxy_pass http://localhost:8001/eduservice/;
}
location /eduoss/ {
proxy_pass http://localhost:8002/;
}
location /vod/ {
proxy_pass http://localhost:8003/;
}
}
}