[英]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.