禁用"Cookie"响应json时的标头 [英] Disable "Cookie" header when responding json

查看:97
本文介绍了禁用"Cookie"响应json时的标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为json响应时,我想禁用(删除)"Cookie"标头.实际上,我可以使用Laravel 4.2在滤镜上设置Config::set('session.driver', 'array').

I'd like to disable (remove) "Cookie" header when responding as json. Actually I could set Config::set('session.driver', 'array') on filter with Laravel 4.2.

如果我在L5(版本5.0.5)中进行过操作,则在日志文件中出现以下错误.

If I did in L5 (version 5.0.5), I got following error at log file.

[YYYY-MM-DD ..:..:..] local.ERROR: exception 'ErrorException' with message 'Undefined index: _sf2_meta' in /foo/bar/vendor/laravel/framework/src/Illuminate/Session/Store.php:280
Stack trace:
#0 /foo/bar/vendor/laravel/framework/src/Illuminate/Session/Store.php(280): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8, 'Undefined index...', '/foo/bar/ve...', 280, Array)
#1 /foo/bar/vendor/laravel/framework/src/Illuminate/Session/Store.php(251): Illuminate\Session\Store->addBagDataToSession()
#2 /foo/bar/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(89): Illuminate\Session\Store->save()
#3 /foo/bar/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(129): Illuminate\Session\Middleware\StartSession->terminate(Object(Illuminate\Http\Request), Object(Illuminate\Http\JsonResponse))
#4 /foo/bar/public/index.php(57): Illuminate\Foundation\Http\Kernel->terminate(Object(Illuminate\Http\Request), Object(Illuminate\Http\JsonResponse))
#5 {main}

事实证明,

推荐答案

好,不再可能在路由中间件中更改会话/cookie驱动程序.您必须在Illuminate\Session\Middleware\StartSession中间件之前指定中间件.

Ok, it turns out, that it is no longer possible to change session/cookie driver within route middlewares. You have to specify the middleware BEFORE Illuminate\Session\Middleware\StartSession middleware.

解决方案: 1.创建自己的中间件:

Solution: 1. Create your own middleware:

class ApiSession implements Middleware{
    public function handle($request, Closure $next){
        $path = $request->getPathInfo();

        if(strpos($path, '/api/') === 0){
            \Config::set('session.driver', 'array');
            \Config::set('cookie.driver', 'array');
        }

        return $next($request);
    }
}

  1. 在会话中间件之前将其添加到内核文件(app/Http/Kernel.php)中:

[..] ApiSession::class, // Check if an API request. If so, set session, cookie drivers Illuminate\Session\Middleware\StartSession::class, [..]

[..] ApiSession::class, // Check if an API request. If so, set session, cookie drivers Illuminate\Session\Middleware\StartSession::class, [..]

不好的地方是您不能将其与路由组一起使用.您必须通过检查当前的URL路径来检查自己是否应用了该中间件.

The bad part is that you cannot use it with route groups. You have to check for your self if this middleware is applied by checking the current url path.

这篇关于禁用"Cookie"响应json时的标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆