我正在使用Reactjs和laravel作为API构建SPA。我使用axios进行API调用,某些请求可以正常工作,但是在某些页面上,当我发出请求时,我会收到一个错误,指出该请求被CORS策略阻止。
在laravel中,我使用spatie/laravel-cors
包添加CORS标头,因此预检请求不会被阻止,默认情况下它将允许来自任何来源的任何类型的请求。
请求:
componentDidMount() {
const url = BACKEND_URL+API+'/XXX/';
let headers = {
"Authorization": "Bearer " + token,
"Content-Type": "application/json",
"Accept": "application/json",
}
axios({
url: url,
method: "GET",
headers: headers,
credentials: 'same-origin',
})
.then(response => {
const data = response.data.data;
this.setState({
data: data,
loading: false
})
})
.catch(error => {
console.log(error);
});
}
预期的响应(来自localhost)
{
campaign_id: XXX
category: []
form_entry: {id: XXX, form_id: XXX, lead_id: XXX, fields: Array(1)}
form_entry_id: XXX
id: XXX
landing__page_id: XXX
last_contacted: "XXX"
name: "XXX"
notes: XXX
status: [{…}]
tag: []
}
错误消息:
Access to XMLHttpRequest at 'XXX.XXX' from origin 'XXX.XXX' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
在本地主机上,在相同的设置下一切正常,奇怪的是,只有将前端和后端都联机后,我才得到错误。
有人知道为什么会这样吗?