自定义请求标头未通过JavaScript获取请求发送

时间:2016-12-01 01:06:13

标签: javascript http xmlhttprequest fetch

我正在尝试使用JavaScripts Fetch() API向我的PHP OAuth服务器发送AJAX请求。

我的问题是我需要使用

发送请求标头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'

这是我现在的代码....

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()
    },

};

“标题”下的“Google Chrome开发者工具网络”标签中的结果是:

一般:

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

响应标题:

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

请求标题:

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

下面的这2张图片显示了使用应用 Postman 发送到网址的相同确切数据,一切正常,因为正确的标头已发送,因此我的服务器响应正确。

enter image description here

此图显示我的服务器返回经过身份验证的资源和标题:

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

在Chrome或Firefox中使用JS Fetch()发出请求时,不显示这些标题!

enter image description here

此外,当我使用插件在我的浏览器中发送自定义标头时,它可以正常工作,因此问题似乎是Fetch()函数不发送我的自定义标头。

如何让JS Fetch()根据我的请求发送自定义标头?

从我在使用Fetch上看到的所有文章中,我似乎已经正确地完成了它,但它没有在Google Chrome或Firefox中发送标题,所以显然它不起作用!我甚至尝试添加 Fetch Pollyfil 只是为了安全起见而没有运气!

2 个答案:

答案 0 :(得分:1)

我终于解决了这个问题。浏览器请求实际上是我的服务器没有返回正确数据的CORS预检请求,这就是为什么fetch从未发送过我的标题。

我现在使用这个Laravel包https://github.com/barryvdh/laravel-cors为PHP laravel应用程序添加cors支持,并且al工作得很好!

答案 1 :(得分:1)

您正在使用mode: 'no-cors',这会阻止浏览器在GET之前发送OPTIONS请求。使用OPTIONS请求浏览器&#34;通知服务器当发送实际请求时,它将与SOME自定义标头一起发送。服务器现在有机会确定是否希望在某些情况下接受请求。&#34;。

Mozilla HTTP OPTIONS method

如果您没有实施这种情况,您的请求将在OPTIONS处死亡。