POST 流明中的 CORS 问题

CORS issue in lumen for POST

我的流明中间件有如下代码

public function handle($request, Closure $next)
{
    //Intercepts OPTIONS requests
    if($request->isMethod('OPTIONS')) {
        $response = response('', 200);
    } else {
        // Pass the request to the next middleware
        $response = $next($request);
    }

    // Adds headers to the response
    $response->header('Access-Control-Allow-Methods', 'HEAD, GET, POST, PUT, PATCH, DELETE');
    $response->header('Access-Control-Allow-Headers', $request->header('Access-Control-Request-Headers'));
    $response->header('Access-Control-Allow-Origin', '*');

    // Sends it
    return $response;
}

我可以使用 postman 发送请求,它也能收到响应。当我通过 vue.js http 方法发送 post 请求时,显示跨源请求被阻止错误。

中间件的一些更改对我有用

public function handle($request, Closure $next)
{
    $allowedDomains = array("http://localhost:8080");
    $origin = $request->server('HTTP_ORIGIN');
    if(in_array($origin, $allowedDomains)){
        //Intercepts OPTIONS requests
        if($request->isMethod('OPTIONS')) {
            $response = response('', 200);
        } else {
            // Pass the request to the next middleware
            $response = $next($request);
        }
        // Adds headers to the response
        $response->header('Access-Control-Allow-Origin', $origin);
        $response->header('Access-Control-Allow-Methods', 'OPTIONS, HEAD, GET, POST, PUT, PATCH, DELETE');
        $response->header('Access-Control-Allow-Headers', $request->header('Access-Control-Request-Headers'));
    }

    // Sends it
    return $response;
}