是否可以访问Service-worker提取请求标题中的令牌?

发布于 2025-02-13 23:01:42 字数 2912 浏览 0 评论 0原文

我想将get请求发送到我的nodejs服务器,包括令牌“授权” 标题。为此,我使用此功能客户端:

// Do a secured GET API request and return response object
async function getJSON(url) {
    try {
        // Send request
        const res = await fetch(url, {
            headers: { Authorization: localStorage.getItem('token') }
        });

        // If something went wrong
        if (!res.ok) {
            // If token is invalid
            if (res.status === 401) {
                // Logout
                localStorage.removeItem('token');
                location.replace(`/?msg=${dict.get('expired-session')}`);
            }

            // Return an object with error message and status code
            return { error: res.statusText, status: res.status };
        }

        // Else return response object
        else return await res.json();
    } catch (err) {
        // Return an object with error message
        return { error: err.message };
    }
}

它可以正常工作,但是我使用服务工作者来缓存请求,并且我不希望将API请求缓存,所以我可以检查<<代码>“授权” 的存在:

// Fetch event
self.addEventListener('fetch', e => e.respondWith(respond(e)));

async function fetchAndCache(req, cache_name) {
    const { url, headers } = req;
    console.log({ url, headers });

    // Fetch request
    const fetch_res = await fetch(req);

    const is_get = req.method === 'GET';
    const is_api = req.headers.Authorization;
    const is_cahing_domain = cache_domains.some(domain => req.url.includes(domain));

    if (is_cahing_domain && is_get && !is_api) {
        // Open cache and save a cloned result
        const cache = await caches.open(cache_name);
        cache.put(req, fetch_res.clone());
    }

    return fetch_res;
}

async function respond(e) {
    if (!use_cache) return fetch(e.request);

    // Try to get response from cache
    const cached_res = await caches.match(e.request);

    // If response is found, return it
    if (cached_res) return cached_res;

    // If request is not found, try to fetch it
    return await fetchAndCache(e.request, 'main');
}

不幸的是,日志显示空标头:

”

即使服务器确实得到了令牌和cached(自从条件不起作用)请求还包括:

我搜索了几个小时,在类似问题中尝试了所有解决方案(在这里在这里),但无效。请帮忙。

I want to send a GET request including a token "Authorization" header to my nodejs server. For this, I use this function client-side:

// Do a secured GET API request and return response object
async function getJSON(url) {
    try {
        // Send request
        const res = await fetch(url, {
            headers: { Authorization: localStorage.getItem('token') }
        });

        // If something went wrong
        if (!res.ok) {
            // If token is invalid
            if (res.status === 401) {
                // Logout
                localStorage.removeItem('token');
                location.replace(`/?msg=${dict.get('expired-session')}`);
            }

            // Return an object with error message and status code
            return { error: res.statusText, status: res.status };
        }

        // Else return response object
        else return await res.json();
    } catch (err) {
        // Return an object with error message
        return { error: err.message };
    }
}

It works fine, but I use a service worker to cache requests as they are made and I don't want API requests to be cached, so I though I could just check for the "Authorization"'s presence:

// Fetch event
self.addEventListener('fetch', e => e.respondWith(respond(e)));

async function fetchAndCache(req, cache_name) {
    const { url, headers } = req;
    console.log({ url, headers });

    // Fetch request
    const fetch_res = await fetch(req);

    const is_get = req.method === 'GET';
    const is_api = req.headers.Authorization;
    const is_cahing_domain = cache_domains.some(domain => req.url.includes(domain));

    if (is_cahing_domain && is_get && !is_api) {
        // Open cache and save a cloned result
        const cache = await caches.open(cache_name);
        cache.put(req, fetch_res.clone());
    }

    return fetch_res;
}

async function respond(e) {
    if (!use_cache) return fetch(e.request);

    // Try to get response from cache
    const cached_res = await caches.match(e.request);

    // If response is found, return it
    if (cached_res) return cached_res;

    // If request is not found, try to fetch it
    return await fetchAndCache(e.request, 'main');
}

Unfortunately, the logs show empty headers:

Dev tools empty headers log screenshot

Even though the server does get the token and the cached (since the condition does not work) request also includes it:

Dev tools cache response screenshot

I searched for a few hours, tried every solutions in similar questions (here and here) but none worked. Please help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

纸伞微斜 2025-02-20 23:01:44

我不知道授权标题。但是打印标头的正确方法是通过方法2。似乎您正在使用方法1。

console.log("Try 1 to print headers.");
console.log(request.headers);

console.log("Try 2 to print headers.")
for (const pair of event.request.headers.entries()) {
  console.log(pair[0]+ ': '+ pair[1]);
}

console logs < /a>

I don't know about Authorization header. But the right way to print headers is via method 2. It seems like you are using method 1.

console.log("Try 1 to print headers.");
console.log(request.headers);

console.log("Try 2 to print headers.")
for (const pair of event.request.headers.entries()) {
  console.log(pair[0]+ ': '+ pair[1]);
}

Console logs

绿光 2025-02-20 23:01:44

标题{}并不意味着标题为空。这意味着它包含一个未在控制台中详细打印的对象。

您可以访问授权标题:

console.log('AuthorizationHeader is:',headers.get('Authorization'))

Headers {} does not mean that the header is empty. It means that it contains an object which is not printed in detail in your console.

You can access the Authorization header as follow:

console.log('AuthorizationHeader is:',headers.get('Authorization'))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文