0

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?

Ubaid
  • 431
  • 4
  • 14
  • It could be the underscore in the header name, see this question: https://stackoverflow.com/questions/22856136/why-underscores-are-forbidden-in-http-header-names – Suzana Jan 31 '18 at 13:37
  • Is page on different origin (domain, port, protocol etc) than the request end point? – charlietfl Jan 31 '18 at 13:39

1 Answers1

0

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',
    )
Ubaid
  • 431
  • 4
  • 14