Can I have some help installing a Service Worker on an application stored on the server apex.oracle.com.
Im currently installing the server worker with this code running on page load:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js', {
scope : './'
}).then(function (registration) {
var serviceWorker;
if (registration.installing) {
serviceWorker = registration.installing;
printState('installing');
} else if (registration.waiting) {
serviceWorker = registration.waiting;
printState('waiting');
} else if (registration.active) {
serviceWorker = registration.active;
printState('active');
}
if (serviceWorker) {
printState(serviceWorker.state);
serviceWorker.addEventListener('statechange', function (e) {
printState(e.target.state);
});
}
}).catch (function (error) {
printState(error);
});
}
And i get the errors:
A bad HTTP response code (404) was received when fetching the script.
/pls/apex/apex//mvx/r/72250/files/static/v5/sw.js Failed to load resource: net::ERR_INVALID_RESPONSE
I have to get this application with service worker because i need it to run offline.
Any ideas?
Thanks in advance.
Edit:
Changed the lines:
navigator.serviceWorker.register('/sw.js', {
scope : './'
to
navigator.serviceWorker.register('#WORKSPACE_IMAGES#sw.js', {
scope : './#WORKSPACE_IMAGES#'
And it worked.
Related
Because I add them from the dashboard and fetch them into my flutter app with api
this is my api code:
export async function get_adminData(request) {
let options = {
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
}
};
try {
const results = await wixData.query("Admin")
.eq("url", "specificValue")
.eq("image", "specificValue")
.eq("text", "specificValue")
.eq("article", "specificValue")
.find();
if (results.items.length > 0) {
options.body = results.items;
return ok(options);
} else {
return notFound({});
}
} catch (error) {
options.body = {
"error": error
};
return serverError(options);
}
}
But I can only access collects that are under Wix App Collection.
I am new to wix and flutter so please help.
First and most obvious issue here is usually permissions issue
Try to check everything with this article
https://support.wix.com/en/article/velo-exposing-a-site-api-with-http-functions
Permissions HTTP functions, no matter how they are invoked, always run
with the permissions of an anonymous site visitor.
I am trying to integrate socket.io with strapi. But unfortunately I have been unable to do so without any proper tutorial or documentation covering this aspect.
I followed along with the only resource I found online which is:
https://medium.com/strapi/strapi-socket-io-a9c856e915a6
But I think the article is outdated. I can't seem to run the code mentioned in it without running into tonnes of errors.
Below is my attempt to implement it and I have been trying to connect it through a chrome websocket plugin smart websocket client But I am not getting any response when I try to run the server.
I'm totally in the dark. Any help will be appreciated
module.exports = ()=> {
// import socket io
var io = require('socket.io')(strapi.server)
console.log(strapi.server) //undefined
// listen for user connection
io.on('connect', socket => {
socket.send('Hello!');
console.log("idit")
// or with emit() and custom event names
socket.emit('greetings', 'Hey!', { 'ms': 'jane' }, Buffer.from([4, 3, 3, 1]));
// handle the event sent with socket.send()
socket.on('message', (data) => {
console.log(data);
});
// handle the event sent with socket.emit()
socket.on('salutations', (elem1, elem2, elem3) => {
console.log(elem1, elem2, elem3);
});
});
};
So I found the solution. Yay. I'll put it here just in case anybody needs it.
boostrap.js
module.exports = async () => {
process.nextTick(() =>{
var io = require('socket.io')(strapi.server);
io.on('connection', async function(socket) {
console.log(`a user connected`)
// send message on user connection
socket.emit('hello', JSON.stringify({message: await strapi.services.profile.update({"posted_by"})}));
// listen for user diconnect
socket.on('disconnect', () =>{
console.log('a user disconnected')
});
});
strapi.io = io; // register socket io inside strapi main object to use it globally anywhere
})
};
Found this at: https://github.com/strapi/strapi/issues/5869#issuecomment-619508153_
Apparently, socket.server is not available when the server starts. So you have to make use of process.nextTick that waits for the socket.server to initialize.
I'll also add a few questions that I faced when setting this up.
How do i connect from an external client like nuxt,vue or react?
You just have to connect through "http://localhost:1337" that is my usual address for strapi.
I am using nuxt as my client side and this is how set up my socketio on the client side
I first installed nuxt-socket-io through npm
Edited the nuxt.config file as per it's documention
modules:[
...
'nuxt-socket-io',
...
],
io: {
// module options
sockets: [
{
name: 'main',
url: 'http://localhost:1337',
},
],
},
And then i finally added a listener in one of my pages.
created() {
this.socket = this.$nuxtSocket({})
this.socket.on('hello', (msg, cb) => {
console.log('SOCKET HI')
console.log(msg)
})
},
And it works.
A clean way to integrate third-party services into Strapi is to use hooks. They are loaded once during the server boot. In this case, we will create a local hook.
The following example has worked with strapi#3.6.
Create a hook for socket.io at ./hooks/socket.io/index.js
module.exports = strapi => {
return {
async initialize() {
const ioServer = require('socket.io')(strapi.server, {
cors: {
origin: process.env['FRONT_APP_URL'],
methods: ['GET', 'POST'],
/* ...other cors options */
}
})
ioServer.on('connection', function(socket) {
socket.emit('hello', `Welcome ${socket.id}`)
})
/* HANDLE CLIENT SOCKET LOGIC HERE */
// store the server.io instance to global var to use elsewhere
strapi.services.ioServer = ioServer
},
}
}
Enable the new hook in order for Strapi to load it - ./config/hook.js
module.exports = {
settings: {
'socket.io': {
enabled: true,
},
},
};
That's done. You can access the websocket server inside ./config/functions/bootstrap.js or models' lifecycle hooks.
// ./api/employee/models/employee.js
module.exports = {
lifecycles: {
async afterUpdate(result, params, data) {
strapi.services.ioServer.emit('update:employee', result)
},
},
};
For those who are looking the answer using Strapi version 4
var io = require("socket.io")(strapi.server.httpServer)
Hello every one i'm new in service worker and i'm facing this error
The FetchEvent for "<My Local URL>" resulted in a network error response: the promise was rejected.
i don't know what it means
this is what happens when i click offline and refresh
Offline Issue From Network Tab
and here is my code
self.addEventListener('install', function(event)
{
console.log('[Service Worker] Installing Service Worker ...', event);
event.waitUntil(
caches.open('static')
.then(function(cache) {
console.log('[Service Worker] Precaching App Shell');
cache.add('/src/js/app.js')
})
)
});
self.addEventListener('activate', function(event) {
console.log('[Service Worker] Activating Service Worker ....', event);
return self.clients.claim();
});
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
if (response) {
return response;
} else {
return fetch(event.request);
}
})
);
});
Any Clue I'll Be Appreciated.
In the install event of your service worker, you add to the Cache Storage API only one item /src/js/app.js. And when you try to check how your app works offline, the first thing that is going to be fetched is HTML response for the main page and since it was not added to the cache, you are getting such results.
So you need to add to the Cache Storage all required assets for offline mode, for example, something like this:
self.addEventListener('install', function(event)
{
console.log('[Service Worker] Installing Service Worker ...', event);
event.waitUntil(
caches.open('static')
.then(function(cache) {
console.log('[Service Worker] Precaching App Shell');
cache.addAll([
'/src/js/app.js',
'/src/css/app.css',
'/src/index.html'
]);
})
)
});
...
Please check the path to the assets accordingly to your app.
Hope it will help you!
I have a Ionic 2 app with a proxy I user for development when i use ionic serve. All was working great with this in my config file :
"proxies": [
{
"path": "/apiv2/",
"proxyUrl": "https://myapilink.com/apiv2/"
}
]
And in my Ionic provider :
constructor(public http: Http) {
this.API_URL = "/apiv2";
this.data = {};
}
call(action, entity, params){
return new Promise(resolve => {
let link = this.API_URL;
let data = JSON.stringify({action: action, entity: entity, params: params});
this.http.post(link, data)
.map(res => res.json())
.subscribe(data => {
this.data = data;
resolve(this.data);
}, error => {
console.log(error);
});
});
}
When I run my Ionic project with ionic serve, I can see that the proxies are added :
[09:54:50] Proxy added:/apiv2/ => https://myapilink.com/apiv2/
But when I run my app, when an API call comes, in my network log I only have 500 errors :
POST http://localhost:8100/apiv2/ 500 (Internal Server Error)
But while Ionic server is running, if I go on chrome and enter this URL : http://localhost:8100/apiv2/, I have the result of my API, with my JSON return, so the redirection is made. I don't understand where it's coming from
Thank in advance for any help
There is some guide in github: https://github.com/ionic-team/ionic-cli#service-proxies .
Maybe in the ionic.config.json you should config like this:
"proxies": [
{
"path": "/apiv2/",
"proxyUrl": "https://localhost:8100/apiv2/"
}
]
This registers and works perfectly fine online. But when the server is turned off, and when the page is refreshed, the registered serviceworker no longer shows up in the console and no caches in the cache storage.
if ("serviceWorker" in navigator){
navigator.serviceWorker.register("/sw.js").then(function(registration){
console.log("service worker reg", registration.scope)
}).catch(function(error){
console.log("Error:", error);
})
}
in sw.js
var CACHE_NAME = 'cache-v1';
var urlsToCache = [
'/index.html'
];
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(CACHE_NAME).then(function(cache) {
return cache.addAll(urlsToCache);
})
);
//event.waitUntil(self.skipWaiting());
});
You're properly adding your file to cache, but you're missing returning your cached file on request.
Your sw.js should also have following code:
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);
}
)
);
});
It's from Introduction to service workers.
Morover, you should rather cache / instead of /index.html as usually, you don't hit index.html file directly.
Your service worker doesn't show any console.log when offline, because you don't have any activate code. This article - offline cookbook is very useful to understand details.