我正在为我的公司建立一个内部使用的 PWA。我应该使用什么方法将不记名令牌附加到来自 dom 或 web-worker 的所有请求。
我在发布时使用的这种方法可以按预期工作form
or json
但我想要一种更干净或更友好的方法,因为我不相信text
后备就足够了。
我正在 Google 的 workbox.js 服务工作模块中寻找一个函数,看看我是否可以设置一个拦截,以便在向我的服务器发出请求时始终附加不记名令牌,因为这将解决为什么我首先在这里结束的问题地方。该代码基于Firebase Service Worker 设置 https://firebase.google.com/docs/auth/web/service-worker-sessions?authuser=0。并且没有任何东西可以获取并将 post 数据重新添加到新请求中,从而有效地删除整个 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 ) );
} );
总而言之,我的问题是......Is the text()
当 POST 的 contentType 都不是时我添加的后备JSON
or FormData
要覆盖所有角度还是我应该考虑一种传输 POST 正文的新方法.