0

我正在用 Lumen 编写 API。所有 GET API 都在使用 axios 的 ReactJS 中运行良好。但是,POST API 不起作用。我通过创建中间件启用了 Lumen 中的 cors,并在 web.php 路由文件中使用它们。但是,仍然得到同样的错误。我无法调试它来自客户端或服务器端的问题。

<?php
/**
* Location: /app/Http/Middleware
*/
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){
        $headers = [
            'Access-Control-Allow-Origin'      => '*',
            'Access-Control-Allow-Methods'     => 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Max-Age'           => '86400',
            'Access-Control-Allow-Headers'     => 'Content-Type, Authorization, X-Requested-With'
        ];
        if ($request->isMethod('OPTIONS'))
        {
            return response()->json('{"method":"OPTIONS"}', 200, $headers);
        }
        $response = $next($request);
        foreach($headers as $key => $value)
        {
            $response->header($key, $value);
        }
        return $response;
    }
}

Register the middleware in bootstrap/app.php

$app->routeMiddleware([
    'auth' => App\Http\Middleware\Authenticate::class,
    'localization' => \App\Http\Middleware\Localization::class,
    'cors' => App\Http\Middleware\Cors::class
]);

Finally, I put the requests in middleware

$router->group(['middleware' => ['cors']], function () use ($router) {
    # Login API's
    $router->post('/login', 'LoginController@index');
    $router->post('/register', 'UserController@register');
    $router->get('/user/{id}', ['middleware' => 'auth','uses' => 'UserController@get_user']);
});

But, the above solution is not working.

---------------- 错误 --------- 在' http://localhost:8000访问 XMLHttpRequest /login ' from origin ' http://localhost:3000 ' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头. 0.chunk.js:10190 POST http://localhost:8000/login net::ERR_FAILED

4

0 回答 0