I am using React With Redux and I wrote a middleware that comes in handy when I do Ajax calls in Epics. For example, to do a GET
request, I have this getJSON
function.
import {ajax, AjaxResponse} from "rxjs/ajax"; const getJSON = (url: string, headers?: Object): Observable<AjaxResponse> => ajax({ method: "GET", url, responseType: "json", headers, withCredentials: true });
Everything seem to work fine except that Ajax
does not set the headers that contains the access token.
When I step through the code, the headers
object looks like this,
{ Authorization: "Bearer ey-SOME-ACCESS-TOKEN" }
As expected... But when I look through the network calls, it does not contain the specified header with its value.
Parsed:
Accept: */* Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Access-Control-Request-Headers: authorization Access-Control-Request-Method: GET Connection: keep-alive Host: localhost:1337 Origin: http://localhost:3000
Source:
OPTIONS /api/test HTTP/1.1 Host: localhost:1337 Connection: keep-alive Access-Control-Request-Method: GET Origin: http://localhost:3000 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36 Access-Control-Request-Headers: authorization Accept: */* Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9
NOTE: Please don't mark this as duplicate. I know there are similar questions on SO, but none of them seem to work for me.
After 3 days of pulling my hairs and banging my head on the walls, I finally figure out what is the problem, but still not sure why/how. Apparently due to CORS
, there is always OPTION
request is made before the actual POST
or GET
request. Which I already knew and kinda make sense. What does not make sense to me is why the heck it does not contain the headers. If anyone can explain this to me will be eligible for the bounty on this question.
I had to made changes in my back-end to handle OPTION
requests, and it seems to work for now. I can't spend more time of this.
0 comments:
Post a Comment