[英]Laravel Passport and Angular giving me unauthorized on api/login route but works fine on postman?
i am having this problem and have been trying to solve it and search the internet for solution but i didn't find anything helping me, I have this app that have Laravel with Passport on the backend and Angular in the Client side, i am trying to authenticate user through http://localhost:8000/api/login route and it's working fine on postman and giving me the token but on Angular giving me unauthorized and unable to get token, i tried a get request on the laravel api and it's getting me data and showing in Angular so get request is working fine with me the problem is with post request although i have checked the login credentials many times and it's correct我遇到了这个问题,并一直在尝试解决它并在互联网上搜索解决方案,但我没有找到任何帮助我的东西,我有这个应用程序,后端有 Laravel 和 Passport,客户端有 Angular,我正在尝试通过http://localhost:8000/api/login路由对用户进行身份验证,它在邮递员上工作正常并给我令牌,但在 Angular 上给我未经授权且无法获得令牌,我尝试了在 laravel api 上的获取请求,它是获取我的数据并在 Angular 中显示,因此获取请求对我来说工作正常问题出在发布请求上,尽管我已经多次检查登录凭据并且它是正确的
usercontroller.php which contains login method usercontroller.php 包含登录方法
class UserController extends Controller
{
public function __construct()
{
$this->middleware('auth:api')->except(['login' , 'register' , 'get_articles']);
}
public function register(Request $request)
{
$validator = Validator::make($request->all() , [
'name' => 'required|min:3|max:100',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6|max:100',
'c_password' => 'required|same:password'
]);
if($validator->fails())
{
return response()->json(['errors' => $validator->errors()] , 400);
}
$user = new User;
$user->email = $request->input('email');
$user->name = $request->input('name');
$user->password = Hash::make($request->input('password'));
$user->save();
return response()->json(['message' => 'created user successfully'] , 201);
}
public function login(Request $request)
{
if(Auth::attempt(['email' => request('email') , 'password' => request('password')]))
{
$user = Auth::user();
$success['token'] = $user->createToken('myapp')->accessToken;
return response()->json(['success' => $success] , 200);
}
return response()->json(['error' => 'unauthorized'] , 401);
}
Cors.php文件
<?php
namespace App\Http\Middleware;
use Closure;
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, Accept, Authorization, X-Request-With')
->header('Access-Control-Allow-Credentials' , 'true');
}
}
here is login.component.ts这是 login.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Loginform } from '../loginform';
import { LoginService } from '../login.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(private http:HttpClient , private LoginService: LoginService) { }
public submitted = false;
public errorMsg;
public email = "";
public pass = "";
public Loginform = new Loginform(this.email , this.pass);
ngOnInit() {
}
onSubmit() {
this.LoginService.login(this.Loginform).subscribe((data) => {console.log(data)} ,
(error) => {//this.errorMsg = error.statusText
console.log(error)});
this.submitted = true;
}
}
and login.service.ts和 login.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Loginform } from './loginform';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class LoginService {
constructor(private http: HttpClient) { }
public url: string = "http://localhost:8000/api/login";
login(loginform : Loginform) {
return this.http.post(this.url , loginform).pipe(catchError(this.handleError))
}
handleError(error: HttpErrorResponse) {
return throwError(error);
}
}
and here is a snapshot of postman with the same credentials postman snapshot这是邮递员的快照,具有相同的凭据邮递员快照
and a picture for the error in the browser browser以及浏览器浏览器中的错误图片
Maybe this could happen because you're doing two request with different Content-Type: in case of Postman you are using Form-Data with a key-value body, instead in Angular6 service you are trying to send data as JSON.也许这可能是因为您使用不同的 Content-Type 执行两个请求:在 Postman 的情况下,您使用带有键值主体的 Form-Data,而不是在 Angular6 服务中,您尝试将数据作为 JSON 发送。
Two different solutions:两种不同的解决方案:
'Content-Type': 'multipart/form-data'
in Angular6.'Content-Type': 'multipart/form-data'
发送您的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.