Access to XMLHttpRequest at *** from origin ‘null’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource
報錯截圖:

報錯原因:
瀏覽器的同源策略約定我們只能在同源的情況下(即協議,域名,端口相同),才能成功請求數據,這里的目的url和http://localhost:3000/是非同源的,所以瀏覽器報錯,告訴我們跨域了。
解決方式:
當遇到這個問題時,我是使用了中間件代理跨域(基於react),通過啟用一個代理服務器,來接收目的接口提供的數據。
1、手動安裝 http-proxy-middleware中間件
npm i http-proxy-middleware
2、在根目錄創建一個setupProxy.js文件
const proxy = require('http-proxy-middleware')
module.exports = function(app){
app.use(
proxy("/webapi", {
target: "https://name.52byte.com/",//目標地址
changeOrigin: true //設置成true:發送請求頭中host會設置成target
})
)
}
3、利用axios發送請求
axios.post(`/webapi/webbrowser/GetEnglishNameListForWeb`, {
realName: "",
gender: "male",
initialLetter: "",
spell: "0",
pronounce: "0",
popularity: "1",
pageIndex: 0
}).then((response) => {
// handle success
console.log(response.data)
}).catch(error => {
// handle error
console.log(error)
}).then(() => {
// always executed
});
4、最后,獲取數據成功啦

