Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Request Headers not being sent with a JavaScript Fetch Request

I am trying to use JavaScripts Fetch() API to send an AJAX request to my PHP OAuth server.

My issue is that I need to send a Request header Authorization with

'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjM3MWFjZTRiZWE1NmViZDQ5YzQ1OTFkMmJiY2E4NGMwOTM2N2JiMjZmNjZiMmJkOTkxZmE3YmU0NTJjYWZmODBkMmZlYmJhYjFjNzMyMmM1In0.eyJhdWQiOiIxIiwianRpIjoiMzcxYWNlNGJlYTU2ZWJkNDljNDU5MWQyYmJjYTg0YzA5MzY3YmIyNmY2NmIyYmQ5OTFmYTdiZTQ1MmNhZmY4MGQyZmViYmFiMWM3MzIyYzUiLCJpYXQiOjE0ODA1NTE5NzIsIm5iZiI6MTQ4MDU1MTk3MiwiZXhwIjoxNTA3NzY3OTcyLCJzdWIiOiI0Iiwic2NvcGVzIjpbImNydWQtYm9va21hcmstY29sbGVjdGlvbnMiLCJjcnVkLWJvb2ttYXJrLXRhZ3MiLCJjcnVkLWJvb2ttYXJrcyJdfQ.YZWbwDXx4gsUtmvLP1GOY2XUnQ5MC030ymfoV6AYjgQMOqKnsmwrsYrTv5q6MVzo50_SMLipyA9t2VgpZkXj6tOdzA-v9idGnV8JVy-GZeceRlhgl7mpnAe1icI5P62mfhHQiyAdF2cfH6OKsy3ONzyzXRw1_pm-5o_qzcNbUGIATnKr5jXbYElRZZlh7-TUBQ2aSnEsu_fOR2rX5zZ_2dhpAMyE5GOK-UODhjs9PQVLXEEtnlzXyRIdjv-2YTuwJzLryHoooP4N5SncvkBlA6mk0IXVnVnJAMkomnkulofmn1k1niK6Dnzk8OANjbi_uPNbj4W2EtHA0tENNKDfAJ9maiHQZgmpWVk_rkKPrw04BogJNq682mgZhRwYjMM8tD7Rzmrb1DRI8_dM60O5AL5Nm5sxXzKd946OGmMLSQ_OnvAXsAN52KdnlQNW2RzMkFErdrXADMf1g1u7WjH-yo7G9wf-2QMVt8ejrWIbj3_7eBUHIWc4VYg_-IzFMkXl_WXKh12n1RnB62nvyz0IQ5aHbNP0_jIFZixHs0CjuNKikoWguEWfRL78eb2cTyxYMn3E2Yh31RMMaJzF1mM-we05D9WPyQUPKNMuIUQVVRI4GOvny9IJUuGbjcQVLsA-EMbXTBcf9LdRo62gQTNyeCYIshgw3MhX9OazDGK7Xks'

This is the code I have right now....

var app = {

    init: function() {
      this.apitest();
    },

    apitest: function() {

        var request = new Request('http://bookmarkapi.dev/api/user', {
            method: 'GET', 
            mode: 'no-cors',
            headers: new Headers({
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjM3MWFjZTRiZWE1NmViZDQ5YzQ1OTFkMmJiY2E4NGMwOTM2N2JiMjZmNjZiMmJkOTkxZmE3YmU0NTJjYWZmODBkMmZlYmJhYjFjNzMyMmM1In0.eyJhdWQiOiIxIiwianRpIjoiMzcxYWNlNGJlYTU2ZWJkNDljNDU5MWQyYmJjYTg0YzA5MzY3YmIyNmY2NmIyYmQ5OTFmYTdiZTQ1MmNhZmY4MGQyZmViYmFiMWM3MzIyYzUiLCJpYXQiOjE0ODA1NTE5NzIsIm5iZiI6MTQ4MDU1MTk3MiwiZXhwIjoxNTA3NzY3OTcyLCJzdWIiOiI0Iiwic2NvcGVzIjpbImNydWQtYm9va21hcmstY29sbGVjdGlvbnMiLCJjcnVkLWJvb2ttYXJrLXRhZ3MiLCJjcnVkLWJvb2ttYXJrcyJdfQ.YZWbwDXx4gsUtmvLP1GOY2XUnQ5MC030ymfoV6AYjgQMOqKnsmwrsYrTv5q6MVzo50_SMLipyA9t2VgpZkXj6tOdzA-v9idGnV8JVy-GZeceRlhgl7mpnAe1icI5P62mfhHQiyAdF2cfH6OKsy3ONzyzXRw1_pm-5o_qzcNbUGIATnKr5jXbYElRZZlh7-TUBQ2aSnEsu_fOR2rX5zZ_2dhpAMyE5GOK-UODhjs9PQVLXEEtnlzXyRIdjv-2YTuwJzLryHoooP4N5SncvkBlA6mk0IXVnVnJAMkomnkulofmn1k1niK6Dnzk8OANjbi_uPNbj4W2EtHA0tENNKDfAJ9maiHQZgmpWVk_rkKPrw04BogJNq682mgZhRwYjMM8tD7Rzmrb1DRI8_dM60O5AL5Nm5sxXzKd946OGmMLSQ_OnvAXsAN52KdnlQNW2RzMkFErdrXADMf1g1u7WjH-yo7G9wf-2QMVt8ejrWIbj3_7eBUHIWc4VYg_-IzFMkXl_WXKh12n1RnB62nvyz0IQ5aHbNP0_jIFZixHs0CjuNKikoWguEWfRL78eb2cTyxYMn3E2Yh31RMMaJzF1mM-we05D9WPyQUPKNMuIUQVVRI4GOvny9IJUuGbjcQVLsA-EMbXTBcf9LdRo62gQTNyeCYIshgw3MhX9OazDGK7Xks'
            })
        });

      return fetch(request).then(app.checkStatus).then(app.parseJSON);
    },


    checkStatus: function(response) {
      if (response.status >= 200 && response.status < 300) {
        return response
      } else {
        var error = new Error(response.statusText)
        error.response = response
        throw error
      }
    },

    parseJSON: function(response) {
      return response.json()
    },

};

The result of this in Google Chrome Dev Tools Network tab under Headers is this:

General:

Request URL:http://bookmarkapi.dev/api/user
Request Method:GET
Status Code:401 Unauthorized
Remote Address:127.0.0.1:80

Response Headers:

HTTP/1.1 401 Unauthorized
Date: Thu, 01 Dec 2016 00:41:43 GMT
Server: Apache/2.4.10 (Win32) OpenSSL/1.0.1i PHP/5.6.23
X-Powered-By: PHP/5.6.23
Cache-Control: no-cache
Content-Length: 28
Keep-Alive: timeout=5, max=99
Connection: Keep-Alive
Content-Type: application/json

Request Headers:

GET /api/user HTTP/1.1
Host: bookmarkapi.dev
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
accept: application/json
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36
Referer: http://localhost/labs/webdevapp/tmp/tools/lab/manage_bookmark_list_tags.html
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8

These 2 images below show the same exact data being sent to the URL using the app Postman and everything works great as the correct headers get sent so my server responds correctly.

enter image description here

This image shows my server returning the authenticated resources and the headers:

Access-Control-Allow-Headers →Authorization
Access-Control-Allow-Methods →GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin →*

These headers are not shown when making a request with JS Fetch() in Chrome or Firefox!

enter image description here


Also when I use a plugin to send custom headers in my browsers, it works correctly so the issue seems to be with the Fetch() function not send my custom headers.

Any ideas how I can get JS Fetch() to send my custom headers with my request?

From all the articles I have seen on using Fetch, it seems I have done it correctly however it does not send the headers in Google Chrome or Firefox so apparently it is not working! I have even tried adding a Fetch Pollyfil just to be on the safe side with no luck!

like image 284
JasonDavis Avatar asked Oct 29 '22 16:10

JasonDavis


2 Answers

I finally resolved the issue. The browser request was actually the CORS preflight request in which my server was not returning the correct data so that is why fetch never sent my headers.

I now use this Laravel package https://github.com/barryvdh/laravel-cors to add cors support to a PHP laravel app and al is working great!

like image 165
JasonDavis Avatar answered Nov 13 '22 14:11

JasonDavis


You are using mode: 'no-cors', this is prevent browser to sending OPTIONS request before GET. With OPTIONS request browser "notifies the server that when the actual request is sent, it will be sent with SOME custom headers. The server now has an opportunity to determine whether it wishes to accept a request under some circumstances.".

Mozilla HTTP OPTIONS method

if you do not implement that circumstances, your request will die at OPTIONS.

like image 42
Mohsen Beiranvand Avatar answered Nov 13 '22 14:11

Mohsen Beiranvand