javascript CORS 错误仅与 400 个错误请求反应获取请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48499693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CORS Errors only with 400 bad request react fetch request
提问by Shrroy
I'm trying to make 'POST'request in react but i'm getting a few problems regarding CORS. I was just following what console says and fix them in server side[which is PHP] and client sideeverything works fine when the status is 200 but when status 400 it shows
我正在尝试'POST'在反应中提出请求,但我遇到了一些关于 CORS 的问题。我只是按照控制台所说的并在服务器端[即PHP]和客户端修复它们,当状态为 200 时一切正常,但是当状态为 400 时它显示
login:1 Failed to load http://192.168.0.102/API/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 400. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
登录:1 无法加载http://192.168.0.102/API/:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问Origin ' http://localhost:3000'。响应具有 HTTP 状态代码 400。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。
I've tried to add mode: 'no-cors'but that's doesn't work it shows
我试图添加,mode: 'no-cors'但它显示不起作用
Uncaught (in promise) SyntaxError: Unexpected end of input
Uncaught (in promise) SyntaxError: Unexpected end of input
Server Side 'PHP Slimframework' headers:
服务器端“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');
});
Client Side
客户端
src/actions/userActions.js
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)
})
})
}
src/components/layout.js
源代码/组件/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;
here screenshot getting this error only with bad request like 400

Please let me know if I miss out any information.
如果我遗漏了任何信息,请告诉我。
If this has already been asked, I would greatly appreciate if you are able to point me in the right direction.
如果这已经被问到,如果你能指出我正确的方向,我将不胜感激。
Thank you so much!
太感谢了!
采纳答案by Adam
The problem is with your Exceptions on server-side, When you are throwing an error the headers are not set.
问题出在服务器端的异常上,当您抛出错误时,未设置标头。
So what you should do is with error response since you said its working with 200 status code.
所以你应该做的是错误响应,因为你说它使用 200 状态代码。
You should set header with when you are throwing the exceptions.
您应该在抛出异常时设置标头。
$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());
};
};
回答by Mr.Arjun
The problem is with the request you are making!
问题出在您提出的请求上!
The server will not set the 'Access-Control-Allow-Origin'header when you make a bad request, it just rejects it and in turn causing the CORS error.
当您发出错误请求时,服务器不会设置“Access-Control-Allow-Origin”标头,它只会拒绝它,进而导致 CORS 错误。
Fix the bad request cause, missing parameter usually and you are good to go!!!
修复错误的请求原因,通常缺少参数,你很高兴!!!
回答by tolotra
You need to add to your object headers a key Access-Control-Allow-Originwith the value http://localhost:3000(your front end URL), or remove
您需要将Access-Control-Allow-Origin带有值http://localhost:3000(您的前端 URL)的键添加到对象标头中,或删除
-> withHeader('Access-Control-Allow-Origin', 'http://localhost:3000')
in your backend (but this is a security issue)
在您的后端(但这是一个安全问题)

