Ich arbeite an einer React-Anwendung und ich benutze Fetch, um eine Anfrage zu senden. Ich habe kürzlich ein Anmeldeformular erstellt und jetzt integriere ich es mit seiner API. Zuvor akzeptierte die API URL-kodierte Daten und alles lief gut. Aber jetzt, da sich die Anforderung geändert hat und die API Daten in JSON akzeptiert, musste ich den Inhaltstyp-Header von "application/x-www-form-urlencoded" in "application/json" ändern. Aber ich erhalte die folgenden Fehler:Ich kann keine Post-Anfrage senden, wenn der 'Content-Type' auf 'application/json' gesetzt ist
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.
ich auch den ‚Access-Control-Allow-Header‘ in der API festgelegt habe, aber es funktioniert immer noch nicht. Hier ist der entsprechende Code für die Client-Seite:
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);
});
}
Und hier ist der entsprechende API-Code:
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');
}
}
Ich kann es wirklich nicht das Problem herauszufinden. Jede Art von Hilfe wird geschätzt.
http://local.moberries.com/api/v1/candidate ist nicht zugänglich –
Weil es lokal ist. Sie können nicht darauf zugreifen. –