我正在使用React应用程序,并使用提取发送请求。我最近做了一个注册表单,现在我正在将它与它的API进行整合。以前API接受的URL编码数据,它都工作正常。但现在需求已经改变,API以JSON接受数据,我不得不将内容类型的头从'application/x-www-form-urlencoded'改为'application/json'。但我得到以下错误:'Content-Type'设置为'application/json'时无法发送发布请求
Fetch API cannot load http://local.moberries.com/api/v1/candidate . 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
我甚至设置的访问控制允许报头'的API中,但它仍然无法正常工作。下面是客户端的相关代码:
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');
}
}
我真的想不通的问题。任何形式的帮助将不胜感激。
http://local.moberries.com/api/v1/candidate无法访问 –
因为它是本地的。您无法访问它。 –