Adding a custom header to HTTP request using angular.js

前端 未结 8 1848
说谎
说谎 2020-11-27 13:01

I am a novice to angular.js, and I am trying to add some headers to a request:

   var config = {headers: {
            \'Authorization\': \'Basic d2VudHdvcnR         


        
8条回答
  •  囚心锁ツ
    2020-11-27 13:26

    my suggestion will be add a function call settings like this inside the function check the header which is appropriate for it. I am sure it will definitely work. it is perfectly working for me.

    function getSettings(requestData) {
        return {
            url: requestData.url,
            dataType: requestData.dataType || "json",
            data: requestData.data || {},
            headers: requestData.headers || {
                "accept": "application/json; charset=utf-8",
                'Authorization': 'Bearer ' + requestData.token
            },
            async: requestData.async || "false",
            cache: requestData.cache || "false",
            success: requestData.success || {},
            error: requestData.error || {},
            complete: requestData.complete || {},
            fail: requestData.fail || {}
        };
    }
    

    then call your data like this

        var requestData = {
            url: 'API end point',
            data: Your Request Data,
            token: Your Token
        };
    
        var settings = getSettings(requestData);
        settings.method = "POST"; //("Your request type")
        return $http(settings);
    

提交回复
热议问题