An unknown error occurred when fetching the script (Service Worker) - javascript

When going offline, I get the following error by my service worker:
(unknown) #3016 An unknown error occurred when fetching the script
my service worker looks like this:
var version = 'v1'
this.addEventListener('install', function(event){
event.waitUntil(
caches.open(version).then(cache => {
return cache.addAll([
'https://fonts.googleapis.com/icon?family=Material+Icons',
'https://fonts.googleapis.com/css?family=Open+Sans:400,600,300',
'./index.html'
])
})
)
})
this.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(resp) {
// if it's not in the cache, server the regular network request. And save it to the cache
return resp || fetch(event.request).then(function(response) {
return caches.open(version).then(function(cache) {
cache.put(event.request, response.clone())
return response
})
})
})
)
})
It is at top level directory, right next to a manifest importing like this in index.html:
<link rel="manifest" href="/manifest.json">
I import the service worker in my entry js file. And register it right after.
require('tether-manifest.json')
import serviceWorker from 'sw'
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register(serviceWorker)
.then(() => {
// registration worked
}).catch(error => {
throw new Error(error)
})
}
It registers fine. I don't encounter the error until I go offline.
I am using webpack with React, and doing the following in webpack to copy my sw.js file to the dist folder:
loaders: [
{ // Service worker
test: /sw\.js$/,
include: config.src,
loader: 'file?name=[name].[ext]'
},
{ // Manifest
test: /manifest\.json$/,
include: config.src,
loader: 'file?name=[name].[ext]'
}
]
The error doesn't give any information as to what is happening.
Anyone have any idea how to fix this?

I had exactly the same problem, I spent an hour trying to figure it out and it turned out that I had another tab for the same origin left opened somewhere (so using the same shared Service Worker) that had the "Offline" checkbox left checked and that prevented another tabs from requesting sw.js for some reason.
It seems that the offline state is leaking from the tab within Service Worker scope while not being properly reflected nor managed by the other tabs than the one that was turned Offline first.
So make sure you have no other clients running the same Service Worker - you should be able to find them listed in DevTools > Application > Service Workers.

Before trying anything else, check whether your https certificate is invalid or not matching the url you are accessing.
E.g. In my case I was trying to access https://localhost with a certificate that was registered for another domain.
While hitting "proceed" would allow me to enter to the site, this exact error would be printed to the console:
An unknown error occurred when fetching the script

For me this error went away when i added sw.js to the cache upon install. Simply forgot to do that, but it solved the issue.

I had this issue while working in an Angular project. My problem was that I was using Angular CLI's built-in ng serve -prod command.
To make it work, I used ng build -prod and then host the resulting dist folder using http-server

In Chrome, what I did was to check the option Bypass for network and then I was able to reload.

Related

Network related issues are not getting logged on sentry platform

I have integrated Sentry into one of my Next.JS application and I'm also able to see JavaScript related errors like reference or syntax error on Sentry platform.
Though sentry is not logging any network related errors on their platform. Got 403 Forbidden, 404 Not found and 500 internal server error on my network calls, but sentry did not reported any of those.
I have used the following steps for the setup:
Installed the SDK using this command npm install --save #sentry/nextjs
Used the wizard automate the initial steps using this command npx #sentry/wizard -i nextjs
Added all configurations from next.config.js to next.config.wizardcopy.js
Deleted next.config.wizardcopy.js and renamed next.config.wizardcopy.js to next.config.js
I have initialised Sentry both in my client and server file like this
Sentry.init({
dsn: '***',
integrations: [
new CaptureConsole()
],
tracesSampleRate: 1.0
});
I have used CaptureConsole method to capture all errors which are there on console and checked on sentry docs and different online available resources for network related errors but got no help.
Could anybody please help me on the same, what can I more use to get network related errors. In case, if it is not possible, let me know that as well.
In my case I am using reactjs, I added new BrowserTracing() as well. You can try this
import * as Sentry from "#sentry/react";
import { CaptureConsole } from "#sentry/integrations";
import { BrowserTracing } from "#sentry/tracing";
Sentry.init({
dsn: "https://e44884be8781480fa50344a421e5aaba#o4504315282653184.ingest.sentry.io/4504315339210752",
integrations: [
new CaptureConsole(),
new BrowserTracing()
],
// Set tracesSampleRate to 1.0 to capture 100%
// of transactions for performance monitoring.
// We recommend adjusting this value in production
tracesSampleRate: 1.0,
});
The issue was I have used try catch statements on my code there while handling the xhr request and sentry does not log errors which are already handled (used try catch statements), one have to manually log errors on sentry using captureException method in that case

HTTP requests in React app are not working over a network connection, but they are working on localhost

I’ve been building a React app for a while now and have been testing responsiveness across multiple devices.
The React app itself works perfectly fine on my local machine. When accessing the React instance over the network, all HTTP requests fail because it wants to send HTTP requests to port 3000 instead of port 5000 which is what my Node.js server is running on.
[1] Compiled successfully!
[1]
[1] You can now view client in the browser.
[1]
[1] Local: http://localhost:3000
[1] On Your Network: http://192.168.1.122:3000
[0] [nodemon] starting `node server.js`
[1] Compiled successfully!
[1] webpack compiled successfully
[0] Server is running on port 5000
[0] MongoDB Connected!
Example of a request in the React app
// Submit application to database
const storeAndSubmit = (formData) => {
try {
// eslint-disable-next-line
const res = axios({
method: 'post',
headers: {
'Content-Type': 'application/json',
},
url: 'http://localhost:5000/api/applications',
data: formData,
});
dispatch({
type: APPLICATION_SUCCESS,
payload: formData.pageNumber,
});
} catch (err) {
dispatch({
type: APPLICATION_FAIL,
});
}
};
Because I don’t know what IP address React will choose when running my start script, I can’t just hard code the IP address into the request. Is there a React environment variable that can be accessed that has the current local network IP address after the start script has been run? If so, I can use that in my HTTP requests and I think that might work.
Error example over the network
xhr.js:210 POST http://192.168.1.122:3000/api/applications 404 (Not Found)
One thing you can do is proxy your requests by adding the following to your package.json file: "proxy": "http://localhost:5000",
Now in your fetch or Axios calls you can use the following URL '/api/applications' instead of 'http://localhost:5000/api/applications'
You are having a networking issue, so let’s go over it in detail.
You have two processes running on your development machine:
a Node.js HTTP server serving the HTML file which loads the React app on localhost:3000. Let’s call this AppServerProcess
a Node.js HTTP server running a controller/driver for the database on localhost:5000. Let’s call this DbServerProcess
So what happens when you are requesting the web application from another device in the network?
The device will make an HTTP request to http://192.168.1.122:3000, where the AppServerProcess will handle the request and respond with the HTML content and the relevant scripts and assets, which will be loaded by the browser. The code in the JavaScript scripts (the web application), will have the fetch code with a URI of http://localhost:5000, which the device will resolve into itself, where it will fail to find anything.
Now, the computer running both processes (DbServerProcess and AppServerProcess) has at least one IP address on the local network, which is 192.168.1.122. This means that if the DbServerProcess is running on localhost:5000, it should also be available on 192.168.1.122:5000, so the URI that should be hardcoded on fetch is http://192.168.1.122:5000/api/applications.
Note that this will also work when working locally, as the IP address will resolve to itself.
Also note that if the computer running both processes has DHCP configured, this IP address may change subject to that configuration, where you seem to have a misconception of what is happening, because it’s not React that chooses that, and it’s not even the AppServerProcess; it’s the OS which has at least one network interface that has a local IP address assigned by the DHCP server running on the router. If you want this to be static, then that is an OS configuration (pretty straight forward on both Windows, macOS and Linux).
Look for "setting static IP address on {operating_system_name}".
I will assume if you specify the React port while starting your app, you will be able to solve this issue and correct me if I am wrong.
You can just do this on Linux:
PORT=3006 react-scripts start
Or this on Windows:
set PORT=3006 && react-scripts start
Check this answer.
Look into cors-npm for your backend server because that maybe the reason for not connecting.
Later you can maybe use Cloudflare Tunnel for your web server and use that address to access your web server in the react app. The link can be provided as an environment variable for the react. see setup react env variable
Firstly, test if the backend API is working or not via Postman.
http://192.168.1.122:5000/ should work on your case.
=========================================================
After it
Try this code on your frontend after checking the backend is working correctly with Postman.
const api = axios.create({
baseURL: "http://192.168.1.122:5000/api/", //PLEASE CONFIRM IP.
headers: {
'Content-Type': 'application/json',
},
});
const submitApi = async (formData) => api.post('/applications', formData);
const storeAndSubmit = async (formData) => {
try {
const {data} = await submitApi(formData);
if(!!data) {
dispatch({
type: APPLICATION_SUCCESS,
payload: formData.pageNumber,
});
} else {
dispatch({
type: APPLICATION_FAIL,
});
}
} catch(e) {
dispatch({
type: APPLICATION_FAIL,
});
}
}
I think you should check the response on the browser in the device you want to connect to the app from.
With the 404 code, the potential reason may be that the device and your computer are not using the same Wi-Fi modem.
You should not use a domain at all:
url: '/api/applications',
or
url: 'api/applications',
The former dictates api to be served from the domain's root, and the latter requires api to be served from the current page's path. In both cases, schema, domain, and port will be inherited from the current page's URL.
Details are in RFC 2396.
It allows you use your code without changes on any domain, any port, as the hosting architecture is not of the frontend app's concern.
Make a .env file and maybe try this:
REACT_APP_API_ENDPOINT=http://192.168.1.blablabla
You can also do:
"scripts" : {
"start": "REACT_APP_API_ENDPOINT=http://localhost.whatever npm/yarn start"
"start-production": "REACT_APP_API_ENDPOINT=http://production.whatever npm/yarn start"
}
It was taken from How can I pass a custom server hostname using React?.

vercel published sveltekit where vite fails to register serviceworker placed in src folder

This question will need someone from vercel team or sveltekit team as it is related to pwa app that I published to vercel:
1- I placed a minifest1.js file in the "static" folder
2- I placed testserviceworker.js file in the "SRC" folder.
When I run my app locally using my laptop by "npm run build" and "npm run preview", vite registers my serviceworker, my cache is populated and the app is installable as pwa.
When I deploy the same code to vercel, vite fails to register the serviceworker. To experiment I added the serviceworker file to the static folder and added a register button in index.svelte to register the file manully when I press the button.
When I press the button, the serviceworker is registered, I'm able to verify it in dev tools, application tab, cache and able to install my app but my lighthouse report showing pwa part as failed.
So my question is regarding vite registering serviceworker by default upon starting the site. Do I need to add a function in load or onMount with "navigator.serviceWorker.register('testserviceworker.js" or there is some kind of magic configuration in vercel or svelte.config.js to point vite to where the serviceworker.js so it register it upon starting the app?
I added the files for manifest and serviceworker here but I don't think they're relative to my question as it is a configuration issue not code issue:
manifest file:
{
"name": "PWATEST",
"short_name": "PWATESTSHORTNAME",
"start_url": "/",
"scope" : "/",
"background_color": "#1b4079",
"theme_color": "#d62828",
"display": "fullscreen",
"icons": [
{
"src": "/512svelte-welcome.png",
"sizes": "512x512",
"type": "image/png",
"purpose" : "any maskable"
}
]
}
My testserviceworker.js
console.log("*****hello from testserviceworker.js inside static folder********")
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open('v3').then((cache) => {
cache.add(
'./favicon.png'
);
})
);
});
self.addEventListener('activate', function(event) {
console.log("serviceworker activate fn :", event)
});
self.addEventListener('fetch', function(event) {
console.log("fetch fn inside serviceworker.js")
})
Here is the LINK to vercel app running with step by step to test this setup in the home page.
Is there any vercel team member or Sveltekit ninja warriors who can guide me to fix this problem? No one is building websites anymore. Installing pwa is the way to go and Sapper used to include a serviceworker and manifest file by default. For some mysterious reason, vite got involved and that ability disappeared and now after deploying, vite is not able to locate the serviceworker to register it as stated in the sveltekit doc:
Doc-serviceworkers
it's often worth using service workers to speed up navigation by precaching your built JS and CSS.
In SvelteKit, if you have a src/service-worker.js file (or src/service-worker.ts, or src/service-worker/index.js, etc) it will be built with Vite and automatically registered.
In conclusion :
1-How to let vite knows about the serviceworker file in specific location like static folder or scoped to a different part of the app?
2-How to fix vite registering the serviceworker if I place the serviceworker.js in src folder?
Hopefully we will get someone from vercel team or sveltekit team to look into this issue. I found this issue and I can disable it but how to register the serviceworker without pressing a button? Put the code in load or onMount?
The published vercel app link is here again for your convenience.
I ended with registeration in the onMount. Now when the app is loaded, the serviceworker is registered and pwa is installable. It passed the lighthouse checks. All green.
Here is the code for onMount:
import { onMount } from 'svelte';
onMount(async () => {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('testserviceworker.js', { scope: '/' }).then(function(reg) {
// registration worked
console.log('Registration succeeded. Scope is ' + reg.scope);
}).catch(function(error) {
// registration failed
console.log('Registration failed with ' + error);
});
};
});
To recap:
When you publish to vercel -accordning to the sveltekit docs - vite suppose to register the serviceworker for you.
1- Place your serviceworker.js file in the static folder.
2- Add onMount fn and register the serviceworker there.
3- No need to disable vite auto registeration in the svelte.config.js as
instructed in the docs as I didn't disable it and it didn't cause any
issues.
Hopefully sveltekit 1.0 will be released soon. I'm sure majority of these bugs will be ironed out by then.

PWA serviceWorker not always registered

We have in-house built CMS and recently we added PWA to it. Now, when accessing the home page www.ourdomain.com everything is fine, but when accessing an article, we are a news website, someting like www.ourdomain.com/section/article a message appears:
Failed to register a ServiceWorker: A bad HTTP response code (404) was
gwreceived when fetching the script.
First the scope was
./
and in that case ServiceWorker wasn't registered at all.
Now I changed the scope to
/
and not it is registered for the home page but not for any article. I went through docs, reading questions and answers but doesn't seem able to solve this. By they way, PWA installs well on a mobile an works well.
Your service worker js file should preferably be in your root public directory of your app since you're just starting out with PWAs, and specifying the correct scope is essential, Here's a perfect example of installing your service worker from Google PWA guide.
main.js
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js')
.then(function(registration) {
console.log('Registration successful, scope is:', registration.scope);
})
.catch(function(error) {
console.log('Service worker registration failed, error:', error);
});
}
service-worker.js
Expecting that you have /service-worker.js and main.js in your root directory, and if you get to work with manifest, you render the same scope as your start_url
You can try the above installation snippet on your app public root directory.

I am getting error in console "You need to enable JavaScript to run this app." reactjs

I am new to reactjs, I am working on a app. It was running fine, but when I've run npm run build command, I am getting error "You need to enable JavaScript to run this app.". I have made changes in server.js file even I've given "homepage": "./", but it did not solved my issue.
And I've checked by running laravel project, javascript is enabled in browser, also tried different browsers.
Someone please help me to overcome this error.
I received this message when no proxy to the server was specified inside client package.json file.
"proxy": "http://localhost:5000"
(where 5000 should be changed to whatever port number the server was setup to listen to. In my case it also required server restart once added)
I had same problem. My workable solution:
package.json:
"homepage": "."
index.js:
app.use(express.static(__dirname)); //here is important thing - no static directory, because all static :)
app.get("/*", function(req, res) {
res.sendFile(path.join(__dirname, "index.html"));
});
I received this error because an API call that I was making was being blocked because of an invalid API key.
Try to run in other browser and see if it is working.
If it works there then please try below things and refresh your website.
Right click and select Inspect.
Go to Application Tab.
Clear everything from local storage, session storage and cookies.
Refresh your website.
This resolved similar issue in my case and hope it will work for others.
Just make sure that this route must be appeared after at all other routes
app.get("/*", function (req, res) {
res.sendFile(path.resolve(__dirname, '../client/build', 'index.html'));
})
I had the same problem. In my case, the class name wasn't following the patterns (must starts with uppercase). As soon as I corrected it everything started to work well.
Go to your SignIn component or Register component, change the form tag to a div tag OR prevent the form default i.e (e.preventDefault). Also make sure that Javascript is enabled in your browser.
after adding proxy in react package.json restart the reacr server. This works for me.
I had some cookies set in the same url (localhost:8080), probably from a previous development, and it was somehow messing with my React project.
I only found out because (out of despair) I tried with another browser and it worked.
I deleted the cookies and it worked perfectly.
Also a react newbie, I hit this issue. Remembering to add ReactDOM.render(<MyClassName />, document.getElementById("root")); fixed it for me.
In your react project folder install serve if you haven't installed it before;
npm install -g serve
Then serve your project with a static server;
serve -s build
The build is a folder generated by 'npm run build'.
That's it! Visit
http://localhost:5000
by default.
If you are facing the error "You need to enable JavaScript to run this app." in reactjs then 9/10 times there is an issue with your API call. Please cross check API url string, parameters, action type, endpoints, action names, controller names and API call status. You'll be able to find the issue.
verify endpoint url again and again. You'll definitely find a solutions. Also check ur VPN access if you're able to hit the end point.
Go to console --> network tab and see ur API status
Had the same issue, when I was trying serve react static files in node js server. Was missing the following in index.js of server side code.
app.use(express.static(path.resolve(__dirname, '../client/build')));
I had been struggling with this issue the whole morning and after trying all the different hacks of setting up proxy and homepage, it still did not resolve.
And then I checked my js files, and because there was an error which was not being caught while npm start, it was not enabling javascript internally.
How I got to know that this did resolve the issue: Stopping the current run and correcting the issue that was there and then rerunning the server.
I had same problem right now. I forgot to bring ${REACT_APP_API}
before error
const res = await axios.get(`/api/products`)
console.log(res.data)
final solution
const res = await axios.get(`${process.env.REACT_APP_API}/api/products`)
console.log(res.data)
It is case sensitive. Needs to start with upper case:
const router = createBrowserRouter([
{
path: "/",
element: <**I**ndex />,
errorElement: < ErrorPage />,
},{
path: "/login",
element: < **L**ogin />,
},{
path: "/register",
element: < **R**egister />,
}
]);

Categories