前后分離 axios 接 api 跨域問題如圖:
解決辦法:
1. npm start 本地開發環境解決:
在webpack配置文件 /config/index.js 里找到 proxyTable 開啟代理 changeOrigin:true,
proxyTable: { '/api':{ target:'http://xx.xx.xx.xx:5568', changeOrigin:true, pathRewrite:{ '^/api':'/api' } } },
2. npm run build 把 dist 放線上后解決:
nginx 的 配置文件 xx.conf 的 server {} 里加如下:
location /api/ {
# 把 /api 路徑下的請求轉發給真正的后端服務器
proxy_pass http://xx.xx.xx.xx:5568;
# 把host頭傳過去,后端服務程序將收到your.domain.name, 否則收到的是localhost:8080
proxy_set_header Host $http_host;
# 把cookie中的path部分從/api替換成/service
proxy_cookie_path /api /;
# 把cookie的path部分從localhost:8080替換成your.domain.name
proxy_cookie_domain localhost:80 http://xx.xx.xx.xx:5568;
}
重新啟動一下 nginx
/etc/init.d/nginx reload
api 跨域 訪問成功