CORS issue - headers

I am working with an SPA - Vue.js frontend and a Rest API service made with a CakePHP backend.
To consume the API I am using vue-resource and adding these headers to the http-request:

Vue.http.interceptors.push((request, next) => {
  request.headers.set('Authorization', 'Bearer ' + localStorage.getItem('id_token'))
  request.headers.set('Accept', 'application/json')
  next()
})

The “request.headers.set(‘Accept’, ‘application/json’)” seems to be working with checking in the console, but when adding “request.headers.set(‘Authorization’, 'Bearer ’ + localStorage.getItem(‘id_token’))” my header in the console becomes “Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8"

This causes an CORS error due to wrong headers…

I have tested in Postman and it works fine.

GET /api/v1/users HTTP/1.1
Host: xxxx.dk
Accept: application/json
Authorization: Bearer eyJ0eX…6Ss
Cache-Control: no-cache
Postman-Token: 3531f187-db73-19b4-2741-90412ce07c1e

It seems that Vue is somehow “polluting” the headers. Can anybody help me configure correct headers for my requests?

This has nothing to do with Vue, or javascript directly, persay… CORS can definitely reject based on mis-configured headers, or fail on misconfigured headers from the response.

1 Like

Well, you are probably right…
I was just sure that since removing Accept header the login did not work and when adding the token header, the console showed some weird Accept header + CORS issue, that Vue was messing with the headers (Read: My Vue settings were messing…).

Thanks for clearing it out. I will get in touch with the backend guys and make them fix the CORS response.

Now im not sure why this would be happening, but my suggestion is to try using a different (and imo, better) AJAX library called Axios, and see if this situation actually still happens. Because that seems strange. This will help rule out that maybe that Vue-resource library (which im assuming you’re using) perhaps has a bug?

The remote end can certainly respond back and fail CORS check if an invalid header is sent to them for sure, I did originally mis-read what was happening here.

1 Like

Thanks for the suggestion! I am using vue-resource now, but was planning on switching to Axios at some point.
If I encounter any issues that should be reported, I will definitely file an issue.

What was the solution for this? I am strugaling with the same and can not find out what do I missed.