ajax请求中自定义添加请求头

时间:2024-03-08 16:11:13

在使用ajax请求业务接口时需要使用请求头进行身份验证,方式如下:

$(function () {
    $.ajax({
        type: \'GET\',
        url: \'/xxxx-api/openapi/url/getBusinessUrl\',
        data: \'ip=10.10.190.1&bizCode=JDCWFCX\',
        dataType: \'json\',
        beforeSend:function(xhr){
          xhr.setRequestHeader("Authorization","Basic "+"cGluZ2FuOjEyMzQ1Na==");
        },
        success:function (data) {
            console.log(data)
            if (data.errcode == 0) {
                alert("成功");
            }else {
                alert("失败")
            }
        }

    })
})
$(function () {
    $.ajax({
        type: \'GET\',
        url: \'/xxxx-api/openapi/url/getBusinessUrl\',
        data: \'ip=10.10.190.1&bizCode=JDCWFCX\',
        dataType: \'json\',
        headers: {"Authorization","Basic "+"cGluZ2FuOjEyMzQ1Na=="}
        success:function (data) {
            console.log(data)
            if (data.errcode == 0) {
                alert("成功");
            }else {
                alert("失败")
            }
        }

    })
})