gpt4 book ai didi

javascript - 服务人员没有从请求中获取正文

转载 作者:行者123 更新时间:2023-11-30 19:19:56 25 4
gpt4 key购买 nike

所以我有一个用于获取的 service worker:

self.addEventListener('fetch', (event) => {
const requestProcessor = (idToken) => {
let req = event.request;
// For same origin https requests, append idToken to header.
if ((self.location.protocol === 'https:' ||
self.location.hostname === 'localhost') &&
idToken) {

// Clone headers as request headers are immutable.
const headers = new Headers();
for (let entry of req.headers.entries()) {
headers.append(entry[0], entry[1]);
}

// Add ID token to header.
headers.append('Authorization', self.location.origin === getOriginFromUrl(event.request.url) ? `Bearer ${idToken}` : idToken);
try {
req = new Request(req.url, {
method: req.method,
headers: headers,
mode: self.location.origin === getOriginFromUrl(event.request.url) ? 'same-origin' : req.mode,
credentials: req.credentials,
cache: req.cache,
redirect: req.redirect,
referrer: req.referrer,
body: req.body,
bodyUsed: req.bodyUsed,
context: req.context
});
} catch (e) {
console.error(e);
}
}

return fetch(req);
};

event.respondWith(getIdToken().then(requestProcessor));
});

它在另一个文件中被这样调用:

export const makePostRequest = (url = '', params = {}) => {
return fetch(url, {
method: 'POST',
body: JSON.stringify(params),
headers: {
'Content-type': 'application/json'
}
}).then((res) => res).catch((err) => console.log(err));
};

出于某种原因,req.body 在 service worker 中始终未定义。此外,看起来提取请求发生了两次。当我设置断点并单步执行代码时,我可以看到服务 worker 没有从提取中获取任何内容。我不明白。

最佳答案

好的,所以这并不明显。所以经过一些研究,这解决了我的问题:

self.addEventListener('fetch', (event) => {
if (getOriginFromUrl(event.request.url) === 'https://app.example.com') {
const requestProcessor = (idToken) => {
let newRequest = null;

// For same origin https requests, append idToken to header.
if ((self.location.protocol === 'https:' || self.location.hostname === 'localhost') && idToken) {
try {
newRequest = new Request(event.request, {
headers: new Headers({
...event.request.Headers,
'Content-Type': 'application/json',
Authorization: 'Bearer ' + idToken,
})
})
} catch (e) {
console.log(e);
}
}

return fetch(newRequest);
};

/* Fetch the resource after checking for the ID token.
This can also be integrated with existing logic to serve cached files
in offline mode.*/
event.respondWith(getIdToken().then(requestProcessor, requestProcessor));
}
});

我还必须设置模式:

export const makePostRequest = (url = '', params = {}) => {
return fetch(url, {
method: 'POST',
mode: 'cors',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(params)
}).then((res) => res).catch((err) => console.log(err));
};

有两个问题:

  1. 默认情况下,header 的模式设置为no-cors。根据a previous SO回答,我必须将 mode 设置为 cors 以允许包含 body 的非基本 header 。
  2. 另一个问题与 headers 不可变有关。必须对此进行更改才能正确复制。

关于javascript - 服务人员没有从请求中获取正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57583086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com