我试图做出 'POST'
反应请求,但我遇到了一些关于 CORS 的问题。我只是按照控制台所说的进行操作,并在 服务器端[ 即 PHP
] 和 客户端 修复它们,当状态为 200 时一切正常,但当状态为 400 时显示
登录:1 无法加载 http://192.168.0.102/API/ :请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问源“ http://localhost:3000 ”。 响应具有 HTTP 状态代码 400 。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。
我尝试添加 mode: 'no-cors'
但这不起作用
未捕获(承诺)SyntaxError:输入意外结束
服务器端“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/动作/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;
如果我遗漏任何信息,请告诉我。
如果已经有人问过这个问题,如果您能指出正确的方向,我将不胜感激。
太感谢了!
原文由 Liam 发布,翻译遵循 CC BY-SA 4.0 许可协议
问题出在服务器端的“php 异常”,当您抛出错误时,未设置标头。
抛出异常时必须设置一些标头: