laravel后台 jquery ajax 跨域 cookie丢失 已解决

问题一描述:

          前端js域名与后台php api域名不相同,ajax请求时会出现

Image

         原因是服务器端不允许非本域名访问,即 Access-Control-Allow-Origin问题。

解决方法:

        1.添加中间件,其中SESSION_ALLOW_ORIGIN是环境变量,用","分隔的允许域名。

<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $origin = isset($_SERVER['HTTP_ORIGIN'])?$_SERVER['HTTP_ORIGIN']:'http://172.16.55.10:8000';
        $allow_origin = explode(',', env('SESSION_ALLOW_ORIGIN', 'http://172.16.55.10:8000,http://172.16.55.50:8000'));

        $response = $next($request);
        if(in_array($origin, $allow_origin)){
            $response->header('Access-Control-Allow-Origin', $origin);
        }
        $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, Accept, token');
        $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
        $response->header('Access-Control-Allow-Credentials', 'true');
        return $response;

    }
}

        2.在App\Http\Kernel.php中加入中间件,下面是直接在全局添加,也可以在web或api或其它单独指定。

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\TrustProxies::class,

        \Illuminate\Session\Middleware\StartSession::class,
        \App\Http\Middleware\Cors::class,
    ];

....

        3.上述问题解决。


问题二描述:

$.ajax({
    type: 'POST',
    url: 'http://api.subdomain.com/auth/login',
    data: {
        'email': $('#email').val(),
        'password': $('#password').val()
    },
    success: function(response){
        console.log(response);
    }
});


        ajax 请求时后台获取的sessionid一直在变,导致用户状态不能保存, cookie也设置失败。

        原因是浏览器端未允许跨域请求。

解决方法:

        在请求中加入下面参数即可。

xhrFields: {
        withCredentials: true
    }






        

本博客所有文章如无特别注明均为原创。作者:zz复制或转载请以超链接形式注明转自 沉思录
原文地址《laravel后台 jquery ajax 跨域 cookie丢失 已解决

相关推荐

发表评论

路人甲 表情
Ctrl+Enter快速提交

网友评论(0)