我正在尝试从我的 ionic 3 应用程序到我的 laravel api 进行 POST 登录 api 调用。 但是,当我尝试获取数据时,它会引发错误,我不太确定可能是什么原因。
我的代码 在提供者中
postData(credentials, type){
return new Promise((resolve,reject)=>{
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
this.http.post(
apiUrl+type,
JSON.stringify(credentials),
{ headers: headers }
).subscribe(res=>{
resolve(res.JSON());
}),(err)=>{
reject(err);
}
});
}
从我的登录页面
responseData:any;
userData={"provider":"","email":"","password":""};
login() {
//Get email address and password and validate
this.authService.postData(this.userData,"login").then((result)=>{
this.responseData = result;
localStorage.setItem('userToken',JSON.stringify(this.responseData));
//console.log(this.responseData);
console.log(this.userData);
},(err)=>{
//connection failed message
});
// Once validated go to home page
//this.nav.setRoot(HomePage);
}
所以当我进行 api 调用时,我期待它给我
{"status":200,"msg":"Successfully loged in","token":"Z82VWTdABK9hcEvnng5kGR2NWW9iX1giewX5B6fw8jUFhVpN1OjIZPKGcwq1"}
但我得到的不是这个
POST http://localhost:8100/://localhost:8000/api/login 404 (Not Found)
ERROR Response {_body: "<!DOCTYPE html>↵<html lang="en">↵<head>↵<meta char…//localhost:8000/api/login</pre>↵</body>↵</html>↵", status: 404, ok: false, statusText: "Not Found", headers: Headers, …}headers: Headers_headers: Map(7) {"content-security-policy" => Array(1), "x-content-type-options" => Array(1), "connection" => Array(1), "x-powered-by" => Array(1), "content-length" => Array(1), …}_normalizedNames: Map(7) {"content-security-policy" => "content-security-policy", "x-content-type-options" => "x-content-type-options", "connection" => "connection", "x-powered-by" => "x-powered-by", "content-length" => "content-length", …}__proto__: Objectok: falsestatus: 404statusText: "Not Found"type: 2url: "http://localhost:8100/://localhost:8000/api/login"_body: "<!DOCTYPE html>↵<html lang="en">↵<head>↵<meta charset="utf-8">↵<title>Error</title>↵</head>↵<body>↵<pre>Cannot POST /://localhost:8000/api/login</pre>↵</body>↵</html>↵"__proto__: Bodyconstructor: ƒ Response(responseOptions)toString: ƒ ()__proto__: Object
我确实检查了 postman
localhost:8000/api/login
它给出了成功结果,但当我从我的 ionic 应用程序调用时却没有。
我对 ionic 很陌生,所以不太确定发生了什么,有人可以帮助我吗?
最佳答案
您没有向我们展示您的 apiUrl
的样子,而是根据您收到的错误和网址:
POST http://localhost:8100/://localhost:8000/api/login 404 (Not Found)
听起来您正在尝试在 url 中使用相对路径。您需要提供完整的 url,否则 Angular 将在前面应用 localhost。
所以你的apiUrl
应该看起来像:
apiUrl = 'http://localhost:8000/api/';
在这种情况下,其中type
将是login
。
此外,您不需要在请求中使用 JSON.stringify
:)
关于angular - IONIC post 请求抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48463203/