我发现很难向 laravel api 发送 http post 请求。 GET 方法工作正常,但我在 google chrome 控制台中收到以下错误
Failed to load http://localhost:8000/api/user/auth: 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:8100' is therefore not allowed access.
自从我寻找解决方案以来已经过去了两天。 我在这里找到了ionic官方博客上的帖子https://blog.ionicframework.com/handling-cors-issues-in-ionic/ 但似乎没有帮助。
谢谢
这是我的代码
authUser(email, pass) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
let data = JSON.stringify(
{
"email": email,
"password": pass
}
);
this.http.post(this.API_URL+'user/auth', data, httpOptions).subscribe(data => {
if(data['success']) {
this.user = data['response'];
} else {
this.hasError = data['message'];
console.log(this.hasError);
}
});
}
最佳答案
好吧,我找到了解决方案 我已经更改了 Content-Type: application/json 和数据正文,下面是示例
authUser(email, pass) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded' //updated
})
};
let data = "email="+email+"&password="+pass+""; //updated
this.http.post(this.API_URL+'user/auth', data, httpOptions).subscribe(data => {
if(data['success']) {
this.user = data['response'];
console.log(this.user);
} else {
this.hasError = data['message'];
console.log(this.hasError);
}
});
}
关于angular - Ionic 2/Angular 与 http post 到 laravel api 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48848766/