我正在使用webpack在localhosted服务器上运行reactjs。我需要从我的reactjs应用程序(客户端)到我的后端进行ajax调用,后端也是本地托管服务器但使用不同的端口。当我从邮递员向我的后端提出请求时,没有问题。但是,当我尝试从我的react js应用程序执行相同操作时,我在控制台中出现了此错误:
XMLHttpRequest cannot load http://localhost:8888/api. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
Uncaught (in promise) Error: Network Error
at createError (createError.js:15)
at XMLHttpRequest.handleError (xhr.js:87)
它似乎是一个C.O.R.S问题。经过几个小时的互联网研究后,我无法找到解决方案。
有我的代码
反应:
handleClick(){
console.log('focused')
axios.get('http://localhost:8888/api').then(function(result){
console.log(result)
})
}

webpack config
devServer: {
contentBase: 'http://localhost',
port: 8888,
// Send API requests on localhost to API server get around CORS.
proxy: {
'/api': {
target: {
host: "localhost",
protocol: 'http:',
port: 3000
}
}
}
}

感谢您的帮助
答案 0 :(得分:0)
尝试在没有主持人的情况下拨打电话:
handleClick(){
console.log('focused')
axios.get('/api').then(function(result){
console.log(result)
})
}