XMLHttpRequest cannot load http://www.xxx.com/v1. Response to
preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:3000' is therefore not allowed
access.
前端人員在調接口數據的時候遇到這個問題是不是感覺到腦瓜疼,跨域跨域有又跨域,讓後臺們用CORS...辦法,然後自己就等呀等呢!
其實前端也能解決...
我用 create-react-app 創建的項目,執行了npm run eject 之後 webpack 暴露了...但是不着急
還可以在項目 -- config -- webpackDevServer.config.js 下更改
// 原數據
module.exports = function (proxy, allowedHost) {
return {
...
proxy,
...
}
}
// 更改
module.exports = function (proxy, allowedHost) {
return {
...
proxyproxy: {
'/v1': {
target: 'http://www.xxx.com',
changeOrigin: true,
secure: false,
},
},
...
}
}
// AXIOS地址也要進行下修改
$.ajax({
url:'/v1/code', // 地址不需要寫域名啦
type:'POST',
dataType:'json',
success:function(data){
console.log(data);
},
error:function(error){
console.log(error)
}
})
然後就可以繼續寫代碼啦♪(^∇^*)!
最後附贈兩幅圖
一個是webpackDevServer.config.js更改前
一個是webpackDevServer.config.js更改後的...
有沒有感覺很貼心
O(∩_∩)O哈哈~