简体   繁体   English

Laravel Passport 和 Angular 在 api/login 路由上给我未经授权但在邮递员上工作正常?

[英]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:两种不同的解决方案:

  1. Serialize JSON object from Laravel Controller;从 Laravel 控制器序列化 JSON 对象;
  2. Try to send your data with 'Content-Type': 'multipart/form-data' in Angular6.尝试在 Angular6 中使用'Content-Type': 'multipart/form-data'发送您的数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 angular8 中的 Twilio API 未授权“401 未授权”但在 Postman 上工作正常 - Twilio API in angular8 Not Authorized " 401 Unauthorized" but working fine on Postman 尝试使用Angular访问API时遇到400错误的请求,但是使用PostMan时,它的工作效果很好 - Getting 400 bad request when trying to access an API using Angular, but it works perfectly fine when using PostMan API在邮递员中工作正常,但在angular2中却不能 - API working fine in postman but not in angular2 获取 angular 8 发布 http 请求的问题,Postman 工作正常 - Problems with getting angular 8 to post http request, Postman works fine http.delete 在 Postman 上工作正常,但在 Angular 4/Ionic 3 应用程序上无效 - http.delete works fine on Postman but not on Angular 4/Ionic 3 app 通过 Postman 发送请求工作正常,但不能通过 Angular 客户端 - Sending Request via Postman works fine but not via angular client Angular: JWT 令牌在 Postman 上可以正常工作,但在我的应用程序中却不行 - Angular: JWT Token works fine on Postman but not in my app Web Api 2适用于邮递员,但使用Angular 2失败 - Web Api 2 works with postman but fails with Angular 2 Angular 子路由在直接加载时重定向,在那里导航工作正常 - Angular child route redirects when loaded directly, navigating there works fine Angular MSAL AD 401 在 Angular App 中未经授权,但在 Postman 中 200 Ok - ASP.NET Core Web API - Angular MSAL AD 401 Unauthorized in Angular App but 200 Ok in Postman - ASP.NET Core Web API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM