我正在开发登录模块,前端在 React 中,后端在 PHP 中,但出现 CORS 错误。
我的 Login.js 代码如下:
UserLoginFunction = () =>{
const { UserEmail } = this.state ;
const { UserPassword } = this.state ;
fetch('http://localhost:8080/users-react/api/contact/login.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: UserEmail,
password: UserPassword
})
}).then((response) => response.json())
.then((responseJson) => {
if(responseJson === 'Data Matched')
{
this.props.navigation.navigate('Second', { Email: UserEmail });
}
else{
alert(responseJson);
}
}).catch((error) => {
console.error(error);
});
}
<label>Email</label>
<input type="text" name="email" value={this.state.email} onChange={this.handleChange}/>
<label>Password</label>
<input type="password" name="password" value={this.state.password} onChange={this.handleChange}/>
<button onClick={this.UserLoginFunction} >Login</button>
在我的 login.php 文件中,我把标题放在下面:
header("Access-Control-Allow-Credentials", "true");
header('Access-Control-Allow-Origin', 'http://localhost:3000');
header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
header("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method,
Access-Control-Request-Headers");
我尝试了上述所有这些标头,但仍然出现错误(来自原点' http://localhost:3000 '已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否 'Access-Control-Allow-Origin ' 请求的资源上存在标头。)
请看看,让我知道