用户登录后,我正在 reactjs 中使用 axios 发出发布请求。这里是:
axios.post('https://localhost:3000/api/login/authentication', {
email: email,
password: password
})
.then(response => {
this.props.history.push('/Main')
})
.catch(error => {
console.log(error)
})
它进入错误,我将其记录到控制台。这就是我得到的:
Error: "Network Error"
createErrorhttp://localhost:3000/static/js/0.chunk.js:26742:15 handleErrorhttp://localhost:3000/static/js/0.chunk.js:26293:14
另外,如果有任何帮助,我会在错误之前收到此警告:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:3000/api/login/authentication. (Reason: CORS request did not succeed)
谁能帮我解决这个问题?提前致谢!
原文由 tee 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果您正在使用向后端 API 发出请求的前端应用程序,并且 API 服务器在不同的端口上运行,则您需要在 API 服务器中包含某些标头。
例如,如果您在开发模式下使用 webpack 服务 ReactJS 应用程序,webpack 充当服务器,将 reactJS 应用程序发送到客户端。然后,向 API 服务器发出请求将要求在不同端口上运行的 API 服务器在所有 http 响应中包含 Access-Control-Allow-Origin 标头。
基本上,在生成每个响应之前,您需要将
'Access-Control-Allow-Origin'
设置为localhost:<port you visit in the browser>
。在基本的 Express 应用程序中,您可以将其粘贴到您的
app.js
文件中,例如:注意:如果您可能需要更改
http://localhost:3001
以匹配您在浏览器中访问的端口。编辑:OP 没有使用 express,而是使用 Webpack。问题是:什么是与表达无关的解决方案?
答:解决方案还是一样的:不管你使用的是什么API服务器,只要为每个响应设置响应头即可。
不过,还有另一种涉及 Webpack 的解决方案:
在
package.json
与 webpack 一起提供的前端代码文件中,添加以下内容:"proxy" :"http://localhost:<port API server is running on>"
例如,如果 webpack 正在将您的前端应用程序服务到
localhost:3000
并且您的 api 服务器正在运行localhost:3001
,那么package.json
中的代理将是"proxy":"http://localhost:3001"