【发布时间】:2016-12-24 05:34:56
【问题描述】:
我正在开发一个 React 应用程序,我正在使用 fetch 发送请求。我最近制作了一个注册表单,现在我正在将它与它的 API 集成。以前 API 接受 url 编码的数据,并且一切正常。但是现在要求已经改变并且 API 接受 JSON 格式的数据,我不得不将 content-type 标头从“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');
}
}
我真的无法弄清楚问题所在。任何形式的帮助将不胜感激。
【问题讨论】:
-
因为它是本地的。您无法访问它。
标签: json reactjs cors fetch content-type