向请求添加新标头,同时保留正文

Tre*_*mer 6 javascript service-worker firebase-authentication progressive-web-apps workbox

我正在为我的公司建立一个PWA用于房屋使用.我应该使用什么方法将持有者令牌附加到来自dom或web-worker的所有请求.

此方法张贴时,我使用的作品如预期formjson但我想一个更清洁或友好的方法,因为我不相信,text回退就足够了.

我在Google的workbox.js服务工作者模块中寻找一个功能,看看我是否可以设置一个拦截,以便在向我的服务器发出请求时始终附加Bearer令牌,因为这样可以解决为什么我最先在这里结束的问题地点.此代码基于Firebase Service Worker设置.并且没有任何东西可以获取并重新添加发布数据到新请求,从而有效地丢弃整个POST主体.

这是我最终得到的代码.

self.addEventListener( 'fetch', ( event ) => {
    const requestProcessor = async ( idToken ) => {

        let req = event.request;

        // For same origin https requests, append idToken to header.
        if ( self.location.origin == getOriginFromUrl( event.request.url ) &&
            ( self.location.protocol == 'https:' ||
                self.location.hostname == 'localhost' ) &&
            idToken ) {


            let contentType = req.headers.get( "Content-Type" );

            // 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', 'Bearer ' + idToken );
            try {

                let tmpReq = req.clone();
                let body = "";

                if ( req.body ) {
                    body = req.body;

                } else if ( req.method === "POST" ) {
                    // get the post data if its json
                    if ( contentType === "application/json" ) {
                        // get JSON data
                        let json = await tmpReq.json();
                        body = JSON.stringify( json );

                    // Get the post data if its a submitted form
                    } else if ( contentType === "application/x-www-form-urlencoded" ) {
                        // get Form-Data
                        body = await tmpReq.formData();

                    // Get the post data as plain text as a fallback
                    } else {
                        body = await tmpReq.text();
                    }

                    console.log( "Content", content );
                }

                // create a new request with the Bearer Token and post body
                req = new Request( req.url, {
                    method: req.method,
                    headers: headers,
                    mode: 'same-origin',
                    credentials: req.credentials,
                    cache: req.cache,
                    redirect: req.redirect,
                    referrer: req.referrer,
                    body: body,
                    bodyUsed: req.bodyUsed,
                    context: req.context
                } );

            } catch ( e ) {
                // This will fail for CORS requests. We just continue with the
                // fetch caching logic below and do not pass the ID token.
            }

        }
        return fetch( req );
    };
    // 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 ) );
} );
Run Code Online (Sandbox Code Playgroud)

总而言之,我的问题是...... 当POST的contentType既不是或者将涵盖所有角度时我添加text()后备是否应该考虑转发POST正文的新方法JSONFormData.

Jef*_*ick 7

如果要修改 a Request,保留body但使用 new 或 updated headers,最简单的方法是将原始请求作为第一个参数传递给Request构造函数,其类型为RequestInfo; 它可以是字符串 URL,也可以是现有Request对象。您在第二个参数(类型为 )中指定的任何字段RequestInit都将覆盖原始响应中的字段。

如果您想在保留原始请求中的所有标头的同时添加一个额外的标头值,则会变得有点棘手,因为默认情况下,如果您只在 中提供新值headers,这将覆盖所有原始标头。因此,您需要确保设置headers为原始标题和新标题的组合。

这是一些说明这一点的代码:

// This request might be created implicitly by the web app,
// but let's just create it manually as an example:
const originalRequest = new Request('https://example.com', {
  body: 'shared body',
  method: 'POST',
  headers: {
    'x-header': 'my header value'
  },
});

// Start with the original headers as a baseline:
const modifiedHeaders = new Headers(originalRequest.headers);
// Make any changes you want:
modifiedHeaders.set('Authorization', 'Bearer 12345');

// Create a new request based on the original,
// with the modified headers:
const modifiedRequest = new Request(originalRequest, {
  headers: modifiedHeaders,
});

// Everything else in modifiedRequest should be as-is,
// but the headers will be updated.
// Do whatever you want with modifiedRequest at this point.
Run Code Online (Sandbox Code Playgroud)

需要注意的一点是,使用这种方法,当您构造修改后的请求时,将最终使用原始请求的正文。这在您的用例中应该无关紧要,因为只有body修改后的请求的 最终会被读取(当您将其传递给 时fetch())。如果出于某种原因,您确实需要阅读两个bodys,请先调用clone()原始请求,例如

const modifiedRequest = new Request(originalRequest.clone(), {...});
// The two requests now have independent bodies.
Run Code Online (Sandbox Code Playgroud)