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 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教