PWA not working correctly offline. Uncaught (in promise) TypeError: Failed to fetch - progressive-web-apps

I am trying to convert a simple webpage I have into a PWA in case the site it uses goes down.
I think I have done the majority of the work. The page is installable on my phone and passes all the Chrome lighthouse tests. But I get the following warning,
Web app manifest meets the installability requirements
Warnings: Page does not work offline. The page will not be regarded as installable after Chrome 93, stable release August 2021.
I also get the following warning and error in console,
The FetchEvent for "https://dannyj1984.github.io/index.html" resulted in a network error response: the promise was rejected.
Promise.then (async)
(anonymous) # serviceWorker.js:30
serviceWorker.js:1 Uncaught (in promise) TypeError: Failed to fetch
There is then a warning saying the site cannot be installed as does not work offline. I have read the chrome dev article which says from the chrome release in Aug21 apps that dont work offline wont be installable. But I am stuck on which part of my fetch is causing an issue. The code in my service worker is,
const TGAbxApp = "TG-ABX-App-v1"
const assets = [
//paths to files to add
]
self.addEventListener("install", installEvent => {
installEvent.waitUntil(
caches.open(TGAbxApp).then(cache => {
cache.addAll(assets)
})
)
})
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
return fetch(event.request);
}
)
);
});
The above code for the fetch part of the service worker I took from Google and as I understand it, it first checks if there is data in the cache stored on install, if not it will request it from the network.

https://developer.chrome.com/blog/improved-pwa-offline-detection/
From Chrome 89 March 2021, it gives a warning if this check does not pass:
The installed service worker fetch event returns an HTTP 200 status code (indicating a successful fetch) in simulated offline mode.
So, in your case, the service worker should return a cached 'index.html' when fetch(event.request) is failed.

I've had the same problem. I re enabled the cache through the developer console->network. fixed

Related

Flow testnet getting: An error occurred when interacting with the Access API

I'm trying to make a request to the testnet but getting the following error:
HTTP Request Error: An error occurred when interacting with the Access API.
transport=FetchTransport
error=Failed to fetch hostname=access.devnet.nodes.onflow.org:9000
path=/v1/scripts?block_height=sealed
method=POST
requestBody={
"script":"aW1wb3J0IEZ1bmdpYmxlVG9rZW4gZnJvbSAweDlhMDc2NmQ5M2I2NjA4YjcKaW1wb3J0IEZVU0QgZnJvbSAweGUyMjNkOGE2MjllNDljNjgKCnB1YiBmdW4gbWFpbihhZGRyZXNzOiBBZGRyZXNzKTogVUZpeDY0IHsKICAgIGxldCBhY2NvdW50ID0gZ2V0QWNjb3VudChhZGRyZXNzKQoKICAgIGxldCB2YXVsdFJlZiA9IGFjY291bnQuZ2V0Q2FwYWJpbGl0eSgvcHVibGljL2Z1c2RCYWxhbmNlKSEKICAgICAgICAuYm9ycm93PCZGVVNELlZhdWx0e0Z1bmdpYmxlVG9rZW4uQmFsYW5jZX0+KCkKICAgICAgICA/PyBwYW5pYygiQ291bGQgbm90IGJvcnJvdyBCYWxhbmNlIHJlZmVyZW5jZSB0byB0aGUgVmF1bHQiKQoKICAgIHJldHVybiB2YXVsdFJlZi5iYWxhbmNlCn0=",
"arguments":["eyJ0eXBlIjoiQWRkcmVzcyIsInZhbHVlIjoiMHg1ODA2MjJlNzQ1MTgzYjE2In0="]
}
The base64 decoded script is:
import FungibleToken from 0x9a0766d93b6608b7
import FUSD from 0xe223d8a629e49c68
pub fun main(address: Address): UFix64 {
let account = getAccount(address)
let vaultRef = account.getCapability(/public/fusdBalance)!
.borrow<&FUSD.Vault{FungibleToken.Balance}>()
?? panic("Could not borrow Balance reference to the Vault")
return vaultRef.balance
}
and the arguments are:
{"type":"Address","value":"0x580622e745183b16"}
When I run the following command in the cli, it works: flow scripts execute -n testnet scripts/getFUSDBalance.cdc --arg "Address:580622e745183b16"
not sure why I'm getting issues with this
EDIT:
didn't mention that the error is coming from FCL
Here's the code I'm using to interact with Flow:
async getFUSDBalance(): Promise<Result<number, string>> {
const scriptText = getFUSDBalance as string;
const user = await this.getCurrentUser();
return await flow.query<number>({
cadence: scriptText,
payer: fcl.authz,
authorizations: [fcl.authz],
args: (arg, t) => [
arg(user.addr, t.Address)
]
})
}
flow.query<T> is just a wrapper for fcl.query
It works in the CLI but not from FCL
EDIT 2:
So I found that the real issue I was facing was I was getting this error:
Fetch API cannot load access.devnet.nodes.onflow.org:9000/v1/scripts?block_height=sealed. URL scheme "access.devnet.nodes.onflow.org" is not supported
access.devnet.nodes.onflow.org:9000 is gRPC (I think). I should have been using https://rest-testnet.onflow.org. However, when I change to that I get a CORS violation. I think I read somewhere that you can't access the testnet from localhost (why?), but I deployed to a *.app domain and I'm getting the same error No 'Access-Control-Allow-Origin' header is present on the requested resource. Is the CORS policy not set up for *.app domains?
So turns out changing to https://rest-testnet.onflow.org for the accessNode.api value did work. Not sure why it didn't when I posted the second edit, but whatever. This works for localhost too.

Github pages Deploy Error: Error: Error: Request failed with status code 400 [duplicate]

This error is popping-up intermittently while trying to deploy my github webpages. I have no clue what to do, I already deleted and recreated the repository but the error persists. I have the same problem for all my github pages repositories.
Here is one repository example: https://github.com/cnftstats/borgs
Run actions/deploy-pages#v1
Actor: github-pages[bot]
Action ID: 1998855719
Artifact URL: https://pipelines.actions.githubusercontent.com/odmqpuZ7yGar25NNWIM53v9pBjO9vEwDjecGIYtf9ECZfcxi8V/_apis/pipelines/workflows/1998855719/artifacts?api-version=6.0-preview
{"count":1,"value":[{"containerId":359584,"size":14684160,"signedContent":null,"fileContainerResourceUrl":"https://pipelines.actions.githubusercontent.com/odmqpuZ7yGar25NNWIM53v9pBjO9vEwDjecGIYtf9ECZfcxi8V/_apis/resources/Containers/359584","type":"actions_storage","name":"github-pages","url":"https://pipelines.actions.githubusercontent.com/odmqpuZ7yGar25NNWIM53v9pBjO9vEwDjecGIYtf9ECZfcxi8V/_apis/pipelines/1/runs/21/artifacts?artifactName=github-pages","expiresOn":"2022-06-15T13:26:01.9505756Z","items":null}]}
Creating deployment with payload:
{
"artifact_url": "https://pipelines.actions.githubusercontent.com/odmqpuZ7yGar25NNWIM53v9pBjO9vEwDjecGIYtf9ECZfcxi8V/_apis/pipelines/1/runs/21/artifacts?artifactName=github-pages&%24expand=SignedContent",
"pages_build_version": "bf8f96d22c5dd116a5d94ee24cd398bdda60035f",
"oidc_token": "***"
}
Failed to create deployment for bf8f96d22c5dd116a5d94ee24cd398bdda60035f.
{"message":"Deployment request failed for bf8f96d22c5dd116a5d94ee24cd398bdda60035f due to in progress deployment. Please cancel e92de3f483b775a12d4f784d7cc661ff2847fa62 first or wait for it to complete.","documentation_url":"https://docs.github.com/rest/reference/repos#create-a-github-pages-deployment"}
Error: Error: Request failed with status code 400
Error: Error: Request failed with status code 400
Sending telemetry for run id 1998855719
GitHub Actions is currently experiencing degraded performance and published this on their status page. Therefore, you are most likely experiencing a side effect of the current problems. Other users are reporting the same issue as well. Try again later when the issue has been resolved by GitHub.
Update: More products are now affected and experience degraded performance. Check their status page for more details: https://www.githubstatus.com
[It was a bug of GitHub, happens to all its users---date: 18/03/2022]
It happens to me today too.. :(
Maybe is a bug of GitHub pages: https://github.com/actions/deploy-pages/issues/22
https://github.community/t/pages-deploy-wedged-incorrect-request-failed-due-to-in-progress-deployment/234793/4

ECONNREFUSED during 'next build'. Works fine with 'next dev' [duplicate]

This question already has an answer here:
Fetch error when building Next.js static website in production
(1 answer)
Closed last year.
I have a very simple NextJS 9.3.5 project.
For now, it has a single pages/users and a single pages/api/users that retrieves all users from a local MongoDB table
It builds fine locally using 'next dev'
But, it fails on 'next build' with ECONNREFUSED error
page/users
import fetch from "node-fetch"
import Link from "next/link"
export async function getStaticProps({ params }) {
const res = await fetch(`http://${process.env.VERCEL_URL}/api/users`)
const users = await res.json()
return { props: { users } }
}
export default function Users({ users }) {
return (
<ul>
{users.map(user => (
<li key={user.id}>
<Link href="/user/[id]" as={`/user/${user._id}`}>
<a>{user.name}</a>
</Link>
</li>
))}
</ul>
);
}
pages/api/users
import mongoMiddleware from "../../lib/api/mongo-middleware";
import apiHandler from "../../lib/api/api-handler";
export default mongoMiddleware(async (req, res, connection, models) => {
const {
method
} = req
apiHandler(res, method, {
GET: (response) => {
models.User.find({}, (error, users) => {
if (error) {
connection.close();
response.status(500).json({ error });
} else {
connection.close();
response.status(200).json(users);
}
})
}
});
})
yarn build
yarn run v1.22.4
$ next build
Browserslist: caniuse-lite is outdated. Please run next command `yarn upgrade`
> Info: Loaded env from .env
Creating an optimized production build
Compiled successfully.
> Info: Loaded env from .env
Automatically optimizing pages ..
Error occurred prerendering page "/users". Read more: https://err.sh/next.js/prerender-error:
FetchError: request to http://localhost:3000/api/users failed, reason: connect ECONNREFUSED 127.0.0.1:3000
Any ideas what is going wrong ? particularly when it works fine with 'next dev' ?
Thank you.
I tried the same few days ago and didn't work... because when we build the app, we don't have localhost available... check this part of the doc - https://nextjs.org/docs/basic-features/data-fetching#write-server-side-code-directly - that said: "You should not fetch an API route from getStaticProps..." -
(Next.js 9.3.6)
Just to be even more explicit on top of what Ricardo Canelas said:
When you do next build, Next goes over all the pages it detects that it can build statically, i.e. all pages that don't define getServerSideProps, but which possibly define getStaticProps and getStaticPaths.
To build those pages, Next calls getStaticPaths to decide which pages you want to build, and then getStaticProps to get the actual data needed to build the page.
Now, if in either of getStaticPaths or getStaticProps you do an API call, e.g. to a JSON backend REST server, then this will get called by next build.
However, if you've integrated both front and backend nicely into a single server, chances are that you have just quit your development server (next dev) and are now trying out a build to see if things still work as sanity check before deployment.
So in that case, the build will try to access your server, and it won't be running, so you get an error like that.
The correct approach is, instead of going through the REST API, you should just do database queries directly from getStaticPaths or getStaticProps. That code never gets run on the client anyways, only server, to it will also be slightly more efficient than doing a useless trip to the API, which then calls the database indirectly. I have a demo that does that here: https://github.com/cirosantilli/node-express-sequelize-nextjs-realworld-example-app/blob/b34c137a9d150466f3e4136b8d1feaa628a71a65/lib/article.ts#L4
export const getStaticPathsArticle: GetStaticPaths = async () => {
return {
fallback: true,
paths: (await sequelize.models.Article.findAll()).map(
article => {
return {
params: {
pid: article.slug,
}
}
}
),
}
}
Note how on that example, both getStaticPaths and getStaticProps (here generalized HoC's for reuse, see also: Module not found: Can't resolve 'fs' in Next.js application ) do direct database queries via sequelize ORM, and don't do any HTTP calls to the external server API.
You should then only do client API calls from the React components on the browser after the initial pages load (i.e. from useEffect et al.), not from getStaticPaths or getStaticProps. BTW, note that as mentioned at: What is the difference between fallback false vs true vs blocking of getStaticPaths with and without revalidate in Next.js SSR/ISR? reducing client calls as much as possible and prerendering on server greatly reduces application complexity.

Getting transport error while watching the document in stitch

When I watch the certain ids in the collection using MongoDB watch I am getting error
ERROR Error: Uncaught (in promise): e: (TRANSPORT_ERROR): the request transport encountered an error communicating with Stitch: event source failed to open and will not reconnect; check network log for more details
e: (TRANSPORT_ERROR): the request transport encountered an error communicating with Stitch: event source failed to open and will not reconnect; check network log for more details
It was working till yesterday it started from today
const db = mongoClient.db(environment.databaseName);
const comments = db.collection('collectionName');
this.changeStream = await comments.watch(ids);
this.changeStream.onNext((event) => {
console.log('Watched document changed:', event);
this.fetchData();
});
I expect that whenever the document is changed in the list of ids. Change event should trigger.
This indicates that your app is unable to communicate with the stitch backend, probably because of not internet or poor network

No results for query of Soundcloud API under iOS

When using the SC.get() function of the Soundcloud API instead of a result I receive a "HTTP Error: 0". The same codes is working under Android and in the browser (with same origin policy disabled).
This is the part of the code:
SC.initialize({client_id : "[myclientID]" ,redirect_uri:"[myURI]"});
SC.get('/resolve', {url : '[myURL]'}, function(track, error) {
if (error) alert('Error: ' + error.message);
trackImg[l] = track.artwork_url;
trackID[l] = track.id;
...
});
The URLs are white-listed as external hosts within the projects .plist and the Cordova.plist (the project is still running under phonegap 1.7.0). There is no warning in the Xcode console about blocked URLs..
Strangely enough the app was working fine a couple of weeks ago. The only thing I found changed was that the callback.html for the redirect URI got deleted but I created a new one.