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')

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
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.

@rrd are you using Axios? Is it doing the same as the OP’s problem with the Accept header being changed when adding the Authorization header?

Yes. I use axios and it seems to ignore all custom headers

@rrd I’m assuming this is related to the other post we are conversing in, where you are seeing your custom headers ignored in the preflight (OPTIONS) request.

For others who may come across this thread, you can find my answer here: How to add HEADERS using AXIOS, for a GET request to a RESTFULL API -- IDXpro


Thanks for helping out here!