Laravel REST API 的 Reactjs:请求的资源上不存在 'Access-Control-Allow-Origin' header

Reactjs with Laravel REST API: No 'Access-Control-Allow-Origin' header is present on the requested resource

所以我有一个用 ReactJS 创建的项目。 我正在尝试登录,这是我的 React 代码:

handleClick(event){
var apiBaseUrl = "http://127.0.0.1:8000/api/auth/login";
var self = this;
var payload={
    "email":this.state.email,
    "password":this.state.password
}
axios.post(apiBaseUrl, payload)
.then(function (response) {
    console.log(response);
    if(response.data.code == 200){
        console.log("Login successfull");
        var uploadScreen=[];
        uploadScreen.push(<UploadScreen appContext={self.props.appContext}/>)
        self.props.appContext.setState({loginPage:[],uploadScreen:uploadScreen})
    }
    else if(response.data.code == 204){
        console.log("Username password do not match");
        alert("username password do not match")
    }
    else{
        console.log("Username does not exists");
        alert("Username does not exist");
    }
})
.catch(function (error) {
console.log(error);
});
}

我对React不是很熟悉,刚拿到这段代码here 在我编辑它之前先试一试。 我正在尝试访问我用 Laravel 5.3 创建的 API 但我收到错误:

Failed to load http://127.0.0.1:8000/api/auth/login: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

Error: Network Error at createError (createError.js:16) at XMLHttpRequest.handleError (xhr.js:87)

我搜索了答案,他们说我应该使用 CORS。我有 Laravel 个 CORS。

我的 cors.php 在配置中

'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['*'],
'allowedMethods' => ['*'],
'exposedHeaders' => [],
'maxAge' => 0,
'hosts' => [],

需要对负载进行字符串化。

var payload = JSON.stringify({yourdata: yourdata});

并尝试像这样添加页眉。

var config = {
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  withCredentials: false
}

axios.post(apiBaseUrl, payload, config)