从laravel6和angular 8中的orgin访问XXX处的XMLHttpRequest

我使用laravel6和angular 8 我想通过API将角度项目中的POST请求发送到服务器 但是在使用OPTION请求方法之后,在chrome浏览器中给出了错误:

  

访问“ http://localhost:8000/api/user/register”处的XMLHttpRequest   来自来源“ http://localhost:4200”的信息已被CORS政策阻止:   对预检请求的响应未通过访问控制检查:否   请求中存在“ access-control-allow-origin”标头   资源。

我在App \ Http \ Middleware中创建了一个中间件:

public function handle($request,Closure $next)
{
    return $next($request)
        ->header('access-control-allow-origin','http://localhost:4200')
        ->header('access-Control-Allow-Methods','POST,OPTIONS')
        ->header('access-Control-Allow-Credentials','true')
        ->header('access-Control-Max-Age','10000')
        ->header('access-Control-Allow-Headers','Content-Type,X-Requested-With');
}

然后在内核中定义中间件:app / Http / kernel.php

 'cors' => \App\Http\Middleware\Cors::class,

并定义路线:

Route::group(['prefix' => 'user','middleware' => 'cors'],function () {
  Route::post('login','Api\AuthController@login');
  Route::post('register','Api\AuthController@register');
  Route::group(['middleware' => 'auth:api'],function(){
    Route::post('getUser','Api\AuthController@getUser');
  });
});

但是我再次遇到相同的错误 请帮我解决

xiazai1999 回答:从laravel6和angular 8中的orgin访问XXX处的XMLHttpRequest

请尝试将“ http://localhost:4200”更改为“ *”,

public function handle($request,Closure $next)
{
    return $next($request)
        ->header('Access-Control-Allow-Origin','*')
        ->header('Access-Control-Allow-Methods','POST,OPTIONS')
        ->header('Access-Control-Allow-Credentials','true')
        ->header('Access-Control-Max-Age','10000')
        ->header('Access-Control-Allow-Headers','Content-Type,X-Requested-With');
} 

并在app / Http / kernel.php文件中注册它。

,

例如,首先创建cors中间件

<?php

    namespace App\Http\Middleware;

    use Closure;

    class Cors
    {
        public function handle($request,Closure $next)
        {
            $headers = [
                'Access-Control-Allow-Methods'=> 'POST,GET,OPTIONS,PUT,DELETE','Access-Control-Allow-Headers'=> 'X-Requested-With,Content-Type,Accept,Origin,Authorization','Access-Control-Allow-Origin' => '*'
            ];

            if($request->getMethod() === 'OPTIONS') {
                // The client-side application can set only headers allowed in Access-Control-Allow-Headers
                return \response('',200,$headers);
            }

            $response = $next($request);
            foreach($headers as $key => $value)
                $response->header($key,$value);
            return $response;
        }
    }

然后在数组$ middleware中添加Http / Kernel.php:

protected $middleware = [
        // other middlewares
        Cors::class
    ];

所有类型为OPTIONS的请求将返回带有标头的响应200。

,

我添加了代码图像以为您提供帮助 我认为我做对了所有事情,但是我的问题没有解决 请检查我发送的照片,以便您可能发现我错了

http://localhost:3000/user/login

this is my API code

And this is kernel code

I use base service for send POST request in Angular

and I use Interceptor for handle Http error

本文链接:https://www.f2er.com/3152373.html

大家都在问