×

在JS里如何在ajax中传递token

作者:Terry2022.06.29来源:Web前端之家浏览:7367评论:0
关键词:js

在JS里如何在ajax中传递token。一共有两种方法:

1、放在请求头中

代码如下:

 $.ajax({
                type: "post",
                url: "http:///test/getInfo",
                headers: {      //请求头
                    Accept: "application/json; charset=utf-8",
                    token: "" + token  //这是获取的token
                },
                data:JSON.stringify(jsonDate),
                contentType: "application/json",  //推荐写这个
                dataType: "json",
                success: function(data){
                	console.log('ok');
                },
                error:function(){
                    console.log('error');
                }
})

2、使用beforeSend方法设置请求头

代码如下:

 $.ajax({
                type: "post",
                url: "http://xxx.com/onlinejudge/test/getInfoById",
                beforeSend: function(request) {      //使用beforeSend
                    request.setRequestHeader("token", token);
                     request.setRequestHeader("Content-Type","application/json");
                 },
                data:JSON.stringify(jsonDate),
                dataType: "json",
                success: function(data){
                    console.log('ok');
                },
                error:function(){
                    console.log('error');
                }
})

试试吧!

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/js20220629a1.html

网友评论文明上网理性发言 已有0人参与

发表评论: