设置请求头的jQuery阿贾克斯 [英] Set Request Header jQuery Ajax

查看:228
本文介绍了设置请求头的jQuery阿贾克斯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被困在一个很奇怪的问题,我想在我的AJAX请求到服务发送一个额外的参数的批准,就这样

I'm stuck in a very strange problem, I want to send an extra param Authorization in my ajax request to a service, just like this

Request headers
Authorization: bearer t-3e57cc74-3e7a-4fc7-9bbb-f6c83252db01
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: JSESSIONID=908D73C50F09E75C9A0D674C4CB33D2F; ROUTEID=.1; __unam=3c3246b-13bc693352d-aa1535c-1

不过,使用这种code

But Using this code

headerParams = {'Authorization':'bearer t-7614f875-8423-4f20-a674-d7cf3096290e'};
    obj = {
        type: 'get',
        url: 'https://api.sandbox.slcedu.org/api/rest/v1/students/test1',
        headers: headerParams,
    data: [],
    dataType: 'json',
    processData: false,
    success: function(data) {
        console.log('success');
        console.log(data);
    }
};

  jQuery.ajax(obj);

据发送这样的未传递价值,也是其请求类型成为选项,而不是得到的,这里是控制台日志

It send like this which is not passing the value, also its request type become OPTION instead of GET, here is console log

Accept: */*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Access-Control-Request-Headers  authorization
Access-Control-Request-Method   GET
Connection  keep-alive
Host    api.sandbox.slcedu.org
Origin  http://localhost
User-Agent  Mozilla/5.0 (Windows NT 6.1; rv:17.0) Gecko/20100101 Firefox/17.0

谁能告诉我怎样才能将它传递这样的 授权:承载T-3e57cc74-3e7a-4fc7-9bbb-f6c83252db01

Can anyone tell me how can I pass it like this Authorization: bearer t-3e57cc74-3e7a-4fc7-9bbb-f6c83252db01

感谢

推荐答案

使用beforeSend pre请求回调,我们可以做到这一点。

Using the beforeSend pre-request callback we can achieve this.

$.ajax({
url: 'https://api.sandbox.slcedu.org/api/rest/v1/students/test1',
type: 'GET',
beforeSend: function (xhr) {
    xhr.setRequestHeader('Authorization', 'bearer t-7614f875-8423-4f20-a674-d7cf3096290e');
},
data: {},
success: function () { },
error: function () { },
});

这篇关于设置请求头的jQuery阿贾克斯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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