简体   繁体   中英

AngularJS $http request fails with custom headers

I am trying to add a custom header to my common request like so:

myApp.config(['$httpProvider', function ($httpProvider) {
    // $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
    $httpProvider.defaults.headers.common['test_key'] = 'kkkkk'; 
}]);

Without the above header request works fine. but when added gives the following error:

{
  "data": null,
  "status": -1,
  "config": {
    "method": "GET",
    "transformRequest": [
      null
    ],
    "transformResponse": [
      null
    ],
    "jsonpCallbackParam": "callback",
    "url": "http://localhost:8900/tt/",
    "data": {},
    "headers": {
      "Accept": "application/json, text/plain, */*",
      "test_key": "kkkkk"
    }
  },
  "statusText": "",
  "xhrStatus": "error"
}

On server side I have Django with Django Rest Framework. Server side code is very simple:

from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET'])
def test(request):
    return Response({'ddddddd'})

urlpatterns = [
    url(r'^tt/$', test)
]

What am I doing wrong? How should I add these headers?

Here is how I solved it after looking at the comment by @charlietfl:

  1. Installed django-cors-headers
  2. Added the following:
from corsheaders.defaults import default_headers

    CORS_ALLOW_HEADERS = default_headers + (
        'test_key',
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM