Laravel API不允许我的前端使用React和Redux进行访问

时间:2018-08-14 12:17:47

标签: php reactjs laravel redux cors

我的API是使用Laravel 5.6版构建的,并且我的前端使用React with Redux。尝试连接到API时,我遇到了CORs问题。

  

无法加载http://127.0.0.1:8000/api/login:对预检请求的响应未通过访问控制检查:所请求的资源上没有'Access-Control-Allow-Origin'标头。因此,不允许访问来源“ http://localhost:3000”。如果不透明的响应满足您的需求,请将请求的模式设置为“ no-cors”以在禁用CORS的情况下获取资源。

我尝试应用我发现的解决方案。我有Cors中间件课程:

public function handle($request, Closure $next)
{
    return $next($request)
        ->header("Access-Control-Allow-Origin", "http://localhost:3000") // Already tried with *
        ->header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
        ->header("Access-Control-Allow-Headers", "Content-Type, Authorization");
}

还有Kernel.php

protected $middlewareGroups = [
    ...,
    'api' => [
        ...
        'cors'
    ],
];

protected $routeMiddleware = [
    ...
    'cors' => \App\Http\Middleware\Cors::class
];

路线:

Route::post("/login", "Api\UserController@login");
Route::post("/register", "Api\UserController@register");

Route::prefix("users")->group(function () {
    Route::middleware("auth:api")->group(function () {
        Route::get("me", "Api\UserController@details");
    });
});

动作:

export function login(data) {
  return dispatch => {
    return dispatch({
      [RSAA]: {
        endpoint: "http://127.0.0.1:8000/api/login",
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(data),
        types: [LOGIN, LOGIN_SUCCESS, LOGIN_FAILURE]
      }
    })
  }
}

在请求的标题中,我可以看到发送的CORs方法。那还有什么呢?

enter image description here

3 个答案:

答案 0 :(得分:0)

使用此软件包https://github.com/barryvdh/laravel-cors解决您的cors问题

答案 1 :(得分:0)

在服务器上部署了具有不可知论性设置的react应用后,我遇到了同样的问题。使用软件包laravel-cors配置laravel对我没有帮助。我对服务器的.htaccess进行了如下配置:

Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"  

答案 2 :(得分:0)

请在您的路由文件顶部( api.php )下方添加以下行。它将解决CORS问题。

use Illuminate\Http\Request;

header('Access-Control-Allow-Origin: *');
//Access-Control-Allow-Origin: *
header('Access-Control-Allow-Methods:  POST, GET, OPTIONS, PUT, DELETE');
header('Access-Control-Allow-Headers:  Content-Type, X-Auth-Token, Origin, Authorization');