我正在编写一个HTTP API库,用于Atom Electron.它基于fetch.服务器不受我的控制,但是用PHP编写,我可以看到它以区分大小写的方式检查标头.
我的代码是这样的:
const headers = new Headers();
headers.append('Authorization', `Bearer ${key}`);
const init = {
method: 'GET',
headers: headers
}
const req = new Request(baseUrl + '/items?format=json');
return fetch(req, init);
Run Code Online (Sandbox Code Playgroud)
请求被拒绝并403 FORBIDDEN出错.当我在Electron Newtork面板中查看请求时,请求标头已存在但Authorization已成为authorization.
我知道fetch()只是遵循HTTP标准,但是有一种简单的方法可以fetch()在我提供时发送标头吗?
目前fetch将是toLowercase()所有标头.(这里有一些讨论https://github.com/whatwg/fetch/issues/304关于可选的禁用).
现在,你可能需要使用http://api.jquery.com/jquery.ajax/与header选项.
Ste*_*how -2
使用 fetch 自己并执行类似的操作,如下所示......
const GLOBALS = require('./Globals');
const HEADERS = {
'Accept': 'application/json',
'Content-Type': 'application/json'
};
const resourceURL = '/some/endpoint'
const body = '';
var request = new Request(`${GLOBALS.API_ENDPOINT}${resourceURL}`, {
method: 'GET',
headers: new Headers(Object.assign(HEADERS, {'Authorization': `JWT ${token}`})),
body: body ? JSON.stringify(body) : null
});
return fetch(request)
.then(res => consume)
Run Code Online (Sandbox Code Playgroud)
采用伪伪代码,因为我们传入的一些功能参数在模板文字中进行评估。