問題描述:
前端react-app使用nginx部署到服務器,瀏覽器訪問80端口,頁面請求同一服務器的后臺api,由于端口不同,產生跨域。(域名不同也會跨域)
解決
nginx修改,在監聽80端口的同時,對前端的請求轉發的實際的后臺服務。
//nginx 部分修改
server {
listen 80;
server_name localhost;
location / {
root /webserver;
index index.html index.htm;
autoindex on;
autoindex_exact_size on;
autoindex_localtime on;
}
location /api/ {
proxy_pass http://120.78.202.210:7001/;
}
}
如上,將前端/api
下的請求轉發到配置地址。
//前端代碼修改
const getData = () => {
axios.get("http://120.78.202.210/api/v1/zhihu/topimage/")
.then(res => {
console.log(res)
}).catch(res => {
console.log(res)
})
}
如上,由于直接請求"http://120.78.202.210:7001/v1/zhihu/topimage/
端口不同導致跨域,因此修改全部請求代碼,將/api/
下的請求轉發到實際的服務器。
若是本地調試,可以添加chrome擴展。
image.png