When using workbox background sync plugin i have to create a route to catch the requests. But I want to catch all urls that contains /api/
From Documentation This is the default regex //api/./.json/
registerRoute(
/\/api\/.*\/*.json/,
new NetworkOnly({
plugins: [bgSyncPlugin]
}),
'POST'
);
The regex will match https://example.com /api/test.json
Im trying to do this to match all url that has /api/ in url for example:
https://example.com/api/user/add/ and https://somethingelse.com/api/todo/add/
But for some reason when im doing this:
registerRoute(
new RegExp(/.*\/api\/.*/),
new NetworkOnly({
plugins: [bgSyncPlugin]
}),
'POST'
);
the background sync plugin does not catch the post request. I dont understand why it would not work, the regex does match when testing it in regex101
Why is workbox background sync plugin not working with new RegExp('.*\/api\/.*/')
on https://example.com/api/users/
Also I have confirmed that this is the issue. When matching my domain url specifically it works.
There's some background about this in the Workbox documentation:
Just like with string matching, requests for different origins are treated differently. Instead of matching against any part of the URL, the regular expression must match from the beginning of the URL in order to trigger a route when there's a cross-origin request.
For example, the previous regular expression
new RegExp('/blog/\\d{4}/\\d{2}/.+')
would not match a request forhttps://some-other-origin.com/blog/<year>/<month>/<post title slug>
. If we wanted a route that would match that general path pattern made against both same- and cross-origin requests, using a regular expression with a wildcard (.+
) at the start is one approach:
Because this could end up being awkward, we've started encouraging folks to use callback functions as the criteria instead:
registerRoute(
({url}) => url.pathname.includes('/api/'),
new NetworkOnly({
plugins: [bgSyncPlugin]
}),
'POST'
);