dongwuxie7976 2015-06-02 14:45
浏览 66
已采纳

无法在Laravel 5中为特定路线添加CORS

I am using Laravel 5 for my app and to set the content-type I used CORS Middleware which looks like this.

public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Credentials', 'true')
            ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
            ->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With')
            ->header('Content-Type', 'application/json');

    } 

This is the function in Class CORS.

But, when I return a Blade view, for example the auth/login, I get a plain HTML code in the browser instead of getting the actual view of HTML.

When I change the 'Content-Type' to text/html, the views work, but the apis which return and accept json, doesn't work.

Where am I going wrong?

  • 写回答

1条回答 默认 最新

  • dougou3871 2015-06-02 14:54
    关注

    Your issue is that you're telling the bowser you're sending json, but actually sending it HTML.

    You can get around this by using the following.

    public function handle($request, Closure $next)
    {
        $return = $next($request)
            ->header('Access-Control-Allow-Credentials', 'true')
            ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
            ->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With');
    
        if ($request->wantsJson())
        {
            $return->header('Content-Type', 'application/json');
        }
    
        return $return;
    }
    

    By using the $request->wantsJson() function you're able to tell if the current request is asking to receive json or not, it does this by checking the accepted content-type header. See: https://github.com/laravel/framework/blob/5.0/src/Illuminate/Http/Request.php#L581

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析