3

Repository with the project

I am getting information about blocked access by CORS policy and none of the solutions I looked at seemed to be working.

error message

Access to XMLHttpRequest at 'http://localhost:8000/search' from origin 'http://localhost:8080' has been blocked by CORS policy: No 
'Access-Control-Allow-Origin' header is present on the requested resource.

My server is hosted locally on localhost:8000 and frontend is on loacalhost:8080. I want to post text data in Vue with Axios in file: store.js%43:56 :

   axios.post('http://localhost:8000/search', {
      queryText: 'TEST_TEXT'
   }).then(function (response) {
      // handle success
      console.log(response)
   }).catch(function (response) {
      // handle error
      console.log(response)
   })

the backend is written in Django with Rest API. I followed those instructions but the response is still the same. The view responsible for the response is here and settings were set up here

I do not want to:

  • Disable web security in Chrome
  • Use JSONP
  • Use a third party site to re-route my requests

If anyone would like to run the project just install requirements.txt from main folder and follow README from main and frontend folders.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Yurkee
  • 795
  • 2
  • 9
  • 23
  • Enable CORS on django, this link will help you https://stackoverflow.com/questions/35760943/how-can-i-enable-cors-on-django-rest-framework?noredirect=1&lq=1 – Rajeev Radhakrishnan Sep 26 '19 at 12:00
  • 1
    What’s the HTTP status code of the response? You can use the Network pane in browser devtools to check. Is it a 4xx or 5xx error rather than a 200 OK success response? – sideshowbarker Sep 26 '19 at 12:00
  • @sideshowbarker its `301 Moved Permanently (from disk cache)` @Rajeev Radhakrishnan I believe I did enabled those. – Yurkee Sep 26 '19 at 12:36
  • 1
    Look at the URL in the Location response header in that 301 response, and use that URL as your request URL instead of `http://localhost:8000/search`. Maybe you juse need to add a trailing slash — `http://localhost:8000/search/`. Anyway, it sounds like the `http://localhost:8000/search` server hasn’t been configured to add headers to 3xx responses. The configuration you’ve done so far is probably only adding the headers to 2xx responses. – sideshowbarker Sep 26 '19 at 13:47
  • I'll check it out back at home, may I ask you to add it as an official answer? after checking files I feel that trailing slash might have been the real problem. – Yurkee Sep 26 '19 at 16:12

1 Answers1

2

You need to enable CORS settings in Django look at django-cors-headers.

Also if you are doing session based authentication, you might have to add some extra settings in your headers. I struggled with Angular2 a while back but I think if you face this issue this answer will be relevant for you.

Sadan A.
  • 1,017
  • 1
  • 10
  • 28