[英]CORS Errors only with 400 bad request react fetch request
我试图在反应中发出'POST'
请求,但我遇到了一些关于 CORS 的问题。 我只是按照控制台所说的并在服务器端[即PHP
] 和客户端修复它们,当状态为 200 时一切正常,但是当状态为 400 时它显示
登录:1 无法加载http://192.168.0.102/API/ :请求的资源上不存在“Access-Control-Allow-Origin”标头。 因此,不允许访问 Origin ' http://localhost:3000 '。 响应具有 HTTP 状态代码 400 。 如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。
我尝试添加mode: 'no-cors'
但这不起作用它显示
Uncaught (in promise) SyntaxError: Unexpected end of input
服务器端“PHP Slimframework”标头:
$app->add(function ($req, $res, $next) {
$response = $next($req, $res);
return $response
->withHeader('Access-Control-Allow-Origin', 'http://localhost:3000')
->withHeader('Origin', 'http://localhost:3000')
->withHeader('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, X-Auth-Token')
->withHeader('Access-Control-Allow-Credentials', 'true')
->withHeader('Access-Control-Request-Headers', 'Origin, X-Custom-Header, X-Requested-With, Authorization, Content-Type, Accept')
->withHeader('Access-Control-Expose-Headers', 'Content-Length, X-Kuma-Revision')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
});
客户端
src/actions/userActions.js
export function loginUsers(userData) {
return new Promise((resolve, reject) =>{
fetch(URL,{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
credentials: 'include',
//mode: 'no-cors', // if it's on it will show Uncaught (in promise) SyntaxError: Unexpected end of input
body: JSON.stringify(userData),
})
.then((response) => response.json())
.then((responseJson) =>{
resolve(responseJson);
})
.catch((error) =>{
reject(error)
})
})
}
源代码/组件/layout.js
import React, {Component} from 'react';
import { loginUsers } from '../actions/usersAction';
class Layout extends Component {
constructor(props){
super(props);
this.state = {
username: '',
password: '',
};
this.handleLogin = this.handleLogin.bind(this);
this.onChange = this.onChange.bind(this);
}
onChange(e){
this.setState({ [e.target.name] : e.target.value });
}
handleLogin(){
if (this.state.username && this.state.password){
loginUsers(this.state).then((result) =>{
let responseJSON = result;
console.log(responseJSON);
});
}
}
render() {
return (
<div className="App">
<input type="text" onChange={this.onChange} name="username" />
<input type="password" onChange={this.onChange} name="password" />
<button onClick={this.handleLogin}>Sign in</button>
</div>
);
}
}
export default Layout;
此处的屏幕截图仅在出现错误请求(如 400)时才会出现此错误
如果我遗漏了任何信息,请告诉我。
如果这已经被问到,如果你能指出我正确的方向,我将不胜感激。
非常感谢!
问题出在您提出的请求上!
当您发出错误请求时,服务器不会设置“Access-Control-Allow-Origin”标头,它只会拒绝它,进而导致 CORS 错误。
修复错误的请求原因,通常缺少参数,你很高兴!!!
问题出在服务器端的“php 异常”上,当您抛出错误时,未设置标头。
抛出异常时必须设置一些标头:
$c = new \Slim\Container();
$c['errorHandler'] = function ($c) {
return function ($request, $response, $exception) use ($c) {
return $c['response']->withStatus(500)
->withHeader('Access-Control-Allow-Origin', 'http://localhost:3000')
->withHeader('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, X-Auth-Token')
->withHeader('Access-Control-Allow-Credentials', 'true')
->withHeader('Access-Control-Expose-Headers', 'Content-Length, X-Kuma-Revision')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
->write(exception->getMessage());
};
};
您需要将一个值为http://localhost:3000
(您的前端 URL)的键Access-Control-Allow-Origin
添加到您的对象标头中,或者删除
-> withHeader('Access-Control-Allow-Origin', 'http://localhost:3000')
在您的后端(但这是一个安全问题)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.