Laravel护照和Angular在api/登录路由上给我未经授权的,但在邮递员上工作正常?



我遇到了这个问题,并一直在尝试解决它并在互联网上搜索解决方案,但我没有找到任何帮助我的东西, 我有这个应用程序,后端有带有护照的Laravel,在客户端有Angular, 我正在尝试通过 http://localhost:8000/api/login 路由对用户进行身份验证 它在邮递员和给我令牌上工作正常,但在 Angular 上给我未经授权且无法获得令牌, 我在 Laravel API 上尝试了一个 get 请求,它正在获取我数据并在 Angular 中显示,所以 get 请求对我来说工作正常,问题出在 post 请求上,尽管我已经多次检查了登录凭据并且是正确的

用户控制器.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);
}

科尔斯.php

<?php
namespace AppHttpMiddleware;
use Closure;
class Cors
{
/**
* Handle an incoming request.
*
* @param  IlluminateHttpRequest  $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');
}
}

这里是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;
}
}

和登录.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);
}
}

这是具有相同凭据的邮递员的快照 邮递员快照

以及浏览器中错误的图片 浏览器

也许发生这种情况是因为您正在用不同的内容类型执行两个请求:在Postman的情况下,您将Form-Data与键值主体一起使用,而不是在Angular6服务中,您尝试将数据作为JSON发送。

两种不同的解决方案:

  1. 从 Laravel 控制器序列化 JSON 对象;
  2. 尝试在 Angular6 中使用'Content-Type': 'multipart/form-data'发送数据。

最新更新