Angular 和 Laravel 项目中出现 CORS 错误

问题描述 投票:0回答:1

我正在开发一个使用 Angular 和 Laravel 的 Web 项目。我成功创建了注册表单,从而创建了用户并解决了 CORS 问题。现在我在登录部分面临类似的问题。它无法正常工作,因为它仅在登录时再次出现 CORS 错误,而不是在注册表单中。以下是我的文件的配置方式:

用户控制器:

public function store(Request $request){

$credentials = $request->only('email','password');

if (Auth::attempt($credentials, $request->filled('remember'))) {
    $request->session()->regenerate();

    return redirect()->intended('/');
}
return back()->withErrors([
    'email' => 'The provided credentials do not match our records.',
]);

}

api.php:

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});

Route::post('/users/store', [UserController::class, 'store']);

Cors.php:

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class Cors
{
/**
 * Handle an incoming request.
 *
 * @param  \Closure(\Illuminate\Http\Request): 
(\Symfony\Component\HttpFoundation\Response)  $next
 */
public function handle(Request $request, Closure $next): Response
{
    $response = $next($request);

    $response->headers->set('Access-Control-Allow-Origin', '*');
    $response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE, HEAD');
    $response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');
    return $response;
}

}

这是我从 Angular 获得的服务:

loginUser(userData: any): Observable<any>{
const requestOptions = {
    withCredentials: true
};
return this.http.post('http://localhost:8000/api/users/store', userData, requestOptions);

}


And the error message when I press the button for login:

从源“http://localhost:4200”访问“http://localhost:8000/api/users/store”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:当请求的凭据模式为“include”时,响应中“Access-Control-Allow-Origin”标头的值不能是通配符“*”。 XMLHttpRequest 发起的请求的凭据模式由 withCredentials 属性控制。消息:“http://localhost:8000/api/users/store 的 Http 失败响应:0 未知错误” POST http://localhost:8000/api/users/store net::ERR_FAILED

php angular laravel authentication cors
1个回答
0
投票

将其添加到您的 Cors.php 中:

$response->headers->set('Access-Control-Allow-Credentials', 'true');

© www.soinside.com 2019 - 2024. All rights reserved.