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/;
}
}
}
