我正在研究React应用程序,我正在使用fetch来发送请求。我最近制作了一个Sign Up表单,现在我正在将它与它的API集成。以前,API接受了url编码数据,并且一切正常。但是现在需求已经改变并且API接受JSON中的数据,我不得不将内容类型头从'application / x-www-form-urlencoded'更改为'application / json'。但是我收到以下错误:
Fetch API无法加载http://local.moberries.com/api/v1/candidate。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,'http://localhost:3000'原产地不允许进入。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用CORS的资源。
我甚至在API中设置了“Access-Control-Allow-Headers”,但它仍然无效。以下是客户端的相关代码:
sendFormData() {
let {user} = this.props;
var formData = {
first_name: ReactDOM.findDOMNode(this.refs.firstName).value,
last_name: ReactDOM.findDOMNode(this.refs.lastName).value,
city: ReactDOM.findDOMNode(this.refs.currentCity).value,
country: ReactDOM.findDOMNode(this.refs.currentCountry).value,
is_willing_to_relocate: user.selectedOption,
cities: relocateTo,
professions: opportunity,
skills: skills,
languages: language,
min_gross_salary: minSal,
max_gross_salary: maxSal,
email: ReactDOM.findDOMNode(this.refs.email).value,
password: ReactDOM.findDOMNode(this.refs.password).value
};
var request = new Request('http://local.moberries.com/api/v1/candidate', {
method: 'POST',
mode: 'cors',
headers: new Headers({
'Accept': 'application/json',
'Content-Type': 'application/json'
})
});
var requestBody = JSON.stringify(formData);
console.log(requestBody);
fetch(request, {body: requestBody})
.then(
function (response) {
if (response.status == 200 || response.status == 201) {
return response.json();
} else {
console.log('Failure!', response.status);
}
}).then(function (json) {
var responseBody = json;
console.log(typeof responseBody, responseBody);
});
}
以下是相关的API代码:
class Cors
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers: Origin, Content-Type, application/json');
}
}
我真的无法弄清楚问题。任何形式的帮助将不胜感激。
事实证明,CORS只允许某些特定的内容类型。
Content-Type标头唯一允许的值是:
- 应用程序/ x-WWW窗体-urlencoded
- 多部分/格式数据
- 纯文本/
资料来源:https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
要将内容类型设置为“application / json”,我必须在API中设置自定义内容类型标头。刚删除了最后一个标题并添加了这个标题:
->header('Access-Control-Allow-Headers', 'Content-Type');
它运作良好。
你违反了'Same Origin Policy'。网站www.example.com可能永远无法从任何网站www.example.net加载资源而非自身。
然而,在开发过程中,有时需要能够做到这一点。绕过这个: