跨域請求攜帶Cookie問題 和 layui框架的一些問題解決


最近在使用layui時遇到一些跨域問題,比如上傳或者table請求api數據,跨域請求沒有暴露出來可以增加xhrFields: {withCredentials: true}的參數,這樣服務端是取不到cookie的數據,不過可以曲線救國,比如把cookie數據通過參數傳到服務端或者封裝到head里,另外在網上找到一篇不錯的,親試有效

 

原文鏈接:https://blog.csdn.net/qq_38261174/article/details/90405524

詳細見:https://www.cnblogs.com/nuccch/p/7875189.html

或:https://harttle.land/2016/12/28/cors-with-cookie.html

1.layui框架設置如下:

layui.use(['form', 'laydate', 'table', 'upload'], function () {
            var form = layui.form,
                laydate = layui.laydate,
                table = layui.table,
                upload = layui.upload,
                $ = layui.$;
 
//ajax全局參數設置
            $.ajaxSetup({
//              dataType : "json",
//              contentType : "application/json",
//              headers : {
//                    'Content-Type' : 'application/x-www-form-urlencoded'
//               },
//              同步
//              async:false, // 默認true,異步
 
                // 發送cookie
                xhrFields: {
                    withCredentials: true
                },
                // 請求發送前
                beforeSend: function () {
                    // 發送請求前,可以對data、url等處理
                },
                // 請求返回
                complete: function () {
                    // 返回數據,根據數據調轉頁面等
                }
            });
 
            // 渲染表數據   本來請求不帶cookie,但上面設置了ajax全局參數,所以請求可帶cookie
            table.render({
                elem: '#table',
                url: apiBaseUrl + ...
                cols: tableTitles,
                page: true
                , text: '暫無相關數據'
                , done: function (res, curr, count) {
                    layer.closeAll('loading');
                }               
            });
 
 
 
后台獲取如下:
HttpContext.Request.Cookies.TryGetValue("FaceUserKey", out string userNameOfEcrypt)

2.通過請求頭設置的方法如下:

//ajax全局配置
        $.ajaxSetup({
            headers: {
                "authorization": $.cookie("FeUserKey")
            },
            //xhrFields: {
            //    withCredentials: true
            //},
            //crossDomain: true
        });
 
 
 
后台接收如下:
var userNameOfEcrypt = HttpContext.Request.Headers["authorization"];

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM