如何修复从 axios 响应 reactjs 收到的网络错误

tee*_*tee 9 reactjs axios

用户登录后,我在 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)
})
Run Code Online (Sandbox Code Playgroud)

它进入错误,我将其记录到控制台。这就是我得到的:

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)

任何人都可以帮我解决这个问题吗?提前致谢!

Wil*_*ard 6

如果您使用的前端应用程序向后端 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文件中,例如:

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', 'http://localhost:3001');
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept'
  );
  next();
});
Run Code Online (Sandbox Code Playgroud)

注意:如果您可能需要更改http://localhost:3001以匹配您在浏览器中访问的端口。

编辑:OP 没有使用 express,而是使用 Webpack。问题是:什么是快速不可知的解决方案?

答:解决方案还是一样的:不管你使用的是什么 API 服务器,只要为每个响应设置响应头即可。

不过,还有另一种涉及 Webpack 的解决方案:

package.jsonwebpack 提供的前端代码文件中,添加以下内容:"proxy" :"http://localhost:<port API server is running on>"

例如,如果 webpack 正在为您的前端应用程序提供服务localhost:3000并且您的 api 服务器正在运行localhost:3001,那么代理package.json将是:

"proxy":"http://localhost:3001"