【问题标题】:CORS issue in lumen for POSTPOST 流明中的 CORS 问题
【发布时间】:2017-05-09 13:30:51
【问题描述】:

我的 lumen 中间件有以下代码

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;
}

我可以使用邮递员发送请求,它也得到响应。当我通过 vue.js http 方法发送 post 请求时,显示 Cross-Origin Request Blocked 错误。

【问题讨论】:

  • 你用铬吗? Chrome 会自行阻止跨域请求。
  • 它发生在 chrome 和 firefox 中。我更改了 apache2.conf,它似乎可以正常工作。但是为什么在php中做会失败??
  • 试试这个包来处理cors

标签: php laravel vue.js lumen


【解决方案1】:

中间件的一些变化对我有用

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;
}

【讨论】:

    猜你喜欢
    • 2018-08-10
    • 2021-03-16
    • 2021-03-05
    • 2015-08-20
    • 2019-08-18
    • 2021-04-13
    • 2020-12-20
    • 2016-04-01
    • 2016-07-26
    相关资源
    最近更新 更多