login(){
console.log("Test1");
this.authService.login(this.userForm.value)
.subscribe(
response => {
console.log("Test2");
console.log(response);
if(response === true){
this.router.navigate(['/admin']);
}else {
this.status = "error";
this.message = "Username or password is incorrect";
}
},
error => {
console.log(<any>error);
this.status = "error";
this.message = error ['message'];
}
);
}
Test1将显示在控制台中,但Test2不会。似乎订阅函数永远不会被执行。
函数login()
将由我的Angular Form的提交按钮调用。
如果我提交表单,则会出现错误。使用.catch查看下面的行...错误调用&#34;服务器错误&#34;
login(user: Object): Observable<any>{
return this.http.post('CENSORED LINK TO API', user)
.map((response: Response) => {
let token = response.json().token;
console.log("Response token: " + token);
if(token){
this.token = token;
localStorage.setItem('token', JSON.stringify(this.token));
return true;
} else {
return false;
}
})
.catch((error:any) => Observable.throw(error.json().error || { message: "Server Error"}));
}
答案 0 :(得分:0)
我已经给出了答案。
对于具有相同问题的其他人,请将此行放入laravel api的index.php中。请务必将其粘贴到
行上方$app = require_once __DIR__.'/../bootstrap/app.php';
不要忘记编辑$allowedOrigins
以确保您的POST请求可以访问laravel api的url。
$allowedOrigins = array(
'(http(s)://)?angular-elearning-user(\.)?c9users\.io',
'(http(s)://)?angular-elearning-user(\.)?c9users\.io(\:)8081',
'(http(s)://)?angular-elearning-user(\.)?c9users\.io(\:)8082',
'https://localhost:8081',
'https://localhost:8082'
);
if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN'] != ''){
foreach ($allowedOrigins as $allowedOrigins){
if(preg_match('#' . $allowedOrigins . '#', $_SERVER['HTTP_ORIGIN'])){
header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: GET,PUT,POST,DELETE,OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
break;
}
}
}
并将其放入Cors.php
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','Content-Type, x-xsrf-token');
}
多数民众赞成。
如果您仍有错误,请尝试使用Insomnia或Postman for Google Chrome进行表单POST请求。