sveltekit unwanted favicon request - sveltekit

In SvelteKit App I have:
src/admin/groups
with three pages:
[id].svelte => for example: /admin/groups/1234 to load a group with id 1234
index.svelte => load a list of groups
new.svelte => create new group
by visiting /admin/groups/1234 i got an error due to favicon.png request which is not expected.
Why does it load the favicon in this page request? My config:
preprocess: preprocess(),
kit: {
adapter: adapter()
},
files: {
lib: "src/lib"
},
trailingSlash: 'always'

In app.html changing
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
to
<link rel="icon" href="/favicon.png" />
solved the problem.

Related

How to host multiple React SPA apps on a single ASP.NET Core site?

I'm trying to run multiple React SPA apps using ASP.NET Core 3.1 with the lastest SpaServices extension and have a problem serving static assets. Much of what I've built comes from a similar question at: How to configure ASP.net Core server routing for multiple SPAs hosted with SpaServices but that was related to Angular and an older version of SpaServices.
My code has two React apps, ClientApp and AdminApp and I have configured each using the following startup code:
app.Map("/client", clientApp =>
{
clientApp.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
});
app.Map("/admin", adminApp =>
{
adminApp.UseSpa(spa =>
{
spa.Options.SourcePath = "AdminApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
});
Going to the /client and /admin routes serves the correct React index.html file, but the linked bundled .js files do not load. Here's an example of the final index HTML for the ClientApp SPA:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<base href="/client" />
<title>Client App</title>
</head>
<body>
<h1>Client App</h1>
<div id="root"></div>
<script src="/static/js/bundle.js"></script>
<script src="/static/js/0.chunk.js"></script>
<script src="/static/js/main.chunk.js"></script>
</body>
</html>
The problem is that the links are relative to the root of the site /static/js/bundle.js and need to be relative to the React app's path. The example file paths should be /client/static/js/bundle.js and /admin/static/js/bundle.js, respectively.
How do I get the system that writes the paths into the index.html file to use the correct root path for the static files? Thanks.
Come up with a possible solution. The expectation is that the build SPA will have the contents of its build directory copied into a folder in the wwwroot folder of the .NET Core project that uses the same name as the route the SPA will use. In this case we have two apps, guestuser and payinguser. The mapping in the Configure function will redirect the user request to pull the static files out of the appropriate wwwroot folder.
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.AddSpaStaticFiles();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot"))
});
app.Map("/guestuser", mappedSpa=>
{
mappedSpa.UseSpa(spa =>
{
spa.Options.DefaultPageStaticFileOptions = new StaticFileOptions()
{
FileProvider =
new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/guestuser"))
};
spa.Options.SourcePath = "wwwroot/guestuser";
});
});
app.Map("/payinguser", mappedSpa=>
{
mappedSpa.UseSpa(spa =>
{
spa.Options.DefaultPageStaticFileOptions = new StaticFileOptions()
{
FileProvider =
new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/payinguser"))
};
spa.Options.SourcePath = "wwwroot/payinguser";
});
});
}
Within the ReactJS project you will want to update/add the homepage property to the package.json file for each project to also use the same name as the folder the site will be hosted in under the wwwroot folder. This will update the paths of the generated code to use the pathname in their file references.
{
"name": "guest-user",
"homepage": "guestuser",
...
}

Why am I experiencing this error when publishing my application?

I created an app with npm run build and tried testing on the github page. But I have an error with the way I call the js file. I already changed the files manually in the service worker but I still can't solve it. If anyone wants to take a look, this is the link:
My Service Worker
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read
/* eslint-disable */
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more'
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}
self.addEventListener('fetch', function (e) {
console.log(e.request.url);
e.respondWith(
caches.match(e.request).then(function (response) {
return response || fetch(e.request);
})
);
});
My index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#000000">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="Yeapps PWA">
<meta name="description" content="Yeapps PWA">
<!-- Add meta theme-color -->
<meta name="theme-color" content="#007bff" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.3/css/bulma.min.css">
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
-->
<!-- <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/icons/192X192.png">
<link rel="apple-touch-icon" href="%PUBLIC_URL%//icons/icon-152x152.png"> -->
<link rel="manifest" href="./manifest.json">
<link rel="shortcut icon" href="./icons/192X192.png">
<link rel="apple-touch-icon" href="./icons/icon-152x152.png">
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500&display=swap" />
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css" integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous">
<title>PWA</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<button class="add-button btn btn-danger">Instalar Yeapps</button>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('service-worker.js').then(function (registration) {
console.log('Worker registration successful', registration.scope);
}, function (err) {
console.log('Worker registration failed', err);
}).catch(function (err) {
console.log(err);
});
});
} else {
console.log('Service Worker is not supported by browser.');
}
let deferredPrompt;
const addBtn = document.querySelector('.add-button');
addBtn.style.display = 'none';
window.addEventListener('beforeinstallprompt', (e) => {
// Prevent Chrome 67 and earlier from automatically showing the prompt
e.preventDefault();
// Stash the event so it can be triggered later.
deferredPrompt = e;
// Update UI to notify the user they can add to home screen
addBtn.style.display = 'block';
addBtn.addEventListener('click', (e) => {
// hide our user interface that shows our A2HS button
addBtn.style.display = 'none';
// Show the prompt
deferredPrompt.prompt();
// Wait for the user to respond to the prompt
deferredPrompt.userChoice.then((choiceResult) => {
if (choiceResult.outcome === 'accepted') {
console.log('User accepted the A2HS prompt');
} else {
console.log('User dismissed the A2HS prompt');
}
deferredPrompt = null;
});
});
});
</script>
</body>
</html>

Identity service 4 auto token refresh

I am using identity server 4 with the oidc-client library in an angular 2 web page. The login, logout calls and api calls are all working correctly without any issues. I have recently started trying to get the token auto refresh functionality to work in the web page also. I see that web page defined in silent-redirect is getting created in the iFrame and I see calls to the id4 service but always get a timeout error on the iframe and no new token received.
Any help or suggestions on what I am missing or doing wrong would be greatly appreciated. I have included relevant client side code below.
I do see the token expiring event being triggered.
thanks a lot in advance.
angular2 service
import { UserManager, Log, MetadataService, User, WebStorageStateStore } from 'oidc-client';
export const settings: any = {
authority: 'http://10.3.30.215:8885',
client_id: 'tps',
redirect_uri: 'http://10.3.30.215:4201/auth.html',
response_type: 'id_token token',
automaticSilentRenew: true,
monitorSession: true,
scope: 'openid scope1 scope2 offline_access',
post_logout_redirect_uri: 'http://10.3.30.215:4201',
silent_redirect_uri: 'http://10.3.30.215:4201/silent_renew.html',
loadUserInfo: true
};
public mgr: UserManager = new UserManager(settings);
constructor(private http: Http) {
Log.logger = console;
Log.level = Log.DEBUG;
}
login() {
this.mgr.clearStaleState().then(() => {
this.mgr.signinRedirect();
});
}
silent_renew.html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script src="oidc-client.js"></script>
<script>
new Oidc.UserManager().signinSilentCallback();
</script>
</body>
</html>
Assuming your site is secure with https and you own the frontend, you could possibly do a resource owner password grant implementation with refresh tokens and use angular's built in auth features.
This site has some good info on how to implement an http interceptor. https://ryanchenkie.com/angular-authentication-using-the-http-client-and-http-interceptors.
Your use case might not allow this approach, but it is an option. Hope that helps.

React Builder tool won't set public url correctly

I am trying to build my react app with react's build tool.
npm run build
But when I open the index.html file in the build folder, I can't see anything except a blank page. That's because react builder sets script and css paths wrong.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<link rel="manifest" href="/manifest.json">
<link rel="shortcut icon" href="/favicon.ico">
<title>React App</title>
<style>
</style>
<link href="/static/css/main.5fa823c3.css" rel="stylesheet">
</head>
<body><noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script type="text/javascript" src="/static/js/main.09bdcb2b.js"></script>
</body>
</html>
As you can see, there is slash before every file path. If I fix this by hand, then the script works but the browser cannot find the "service-worker.js" file because value of the process.env.PUBLIC_URL is null. (service-worker.js exists in the right location)
export default function register() {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
window.addEventListener('load', () => {
console.log("URL: "+process.env.PUBLIC_URL) //THIS IS NULL
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and
// the fresh content will have been added to the cache.
// It's the perfect time to display a "New content is
// available; please refresh." message in your web app.
console.log('New content is available; please refresh.');
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
});
}
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}
Basically, it cannot set the public url.
How can I fix this? There is almost no information about this problem anywhere.
You must set your 'homepage' on your package.json file. Assume that your project is in a folder named "project" on the root of your server's working directory.
{
"name": "app name",
"homepage": "/project",
}

Why express returns index.html when app.css is requested?

I serve my Angular app using an express server.
var express = require('express');
var server = express();
server.use(express.static('./app'));
server.all('*', function(req, res) {
res.sendFile('index.html', { root: './app' });
});
server.listen(8000);
Full gulpfile.js is here.
When I navigate to http://localhost:8000, my Angular app redirects to http://localhost:8000/home, and app.css is served properly (I get CSS in the response).
However, if I refresh the page (http://localhost:8000/home), the response for app.css is index.html.
Why is this happening, and how would you fix that?
DEMO HERE
You need to use an absolute path.
<link rel="stylesheet" type="text/css" href="/app.css">
Otherwise the request to express for app.css from /home will be home/app.css not /app.css.

Resources