React Builder tool won't set public url correctly - reactjs

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",
}

Related

sveltekit unwanted favicon request

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.

Getting error when sending POST request - is the PORT correct?

I am trying to sign up the user but I am getting an error back from the server.
VM19:1 POST http://localhost:5001/auth/undefined/auth/signup 404 (Not Found)
//
err: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /auth/undefined/auth/signup</pre>
</body>
</html>
My server settings are below:
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {});
And cors:
app.use(
cors({
credentials: true,
origin: process.env.ORIGIN || "http://localhost:5001",
})
);
On the front end my function looks like this:
const authService = axios.create({
baseURL: `${process.env.SERVER_URL}/auth`,
});
export function signup(credentials) {
return authService
.post("/signup", credentials)
.then(successStatus)
.catch(internalServerError);
}
I don't know whether the issue is related to routing? Also when I set the port for the front end ORIGIN to 3000 it's says that the application is running on this port although it is running on port 5000.
Thanks

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",
...
}

react application not rendering react component in Express

I'm building a MVC Express app using React and node.js .
i have index.html in public folder , and index.jsx in the views folder
then, I start my server, go to localhost and I see a blank page, i tried many solutions and none of them solve the problem
this is file structure
+-- app.js
+-- public
| +-- index.html
+-- routes
| +-- index.js
+-- views
| +-- index.jsx
this is the app.js in the root
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'jsx');
app.engine('jsx', require('express-react-views').createEngine());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
//app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(__dirname + '/public'));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
and this is public/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.2/react.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.2/react-dom.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js" type="text/javascript"></script>
<title>MERN</title>
<meta name="viewport" content="width=device-width">
</head>
<body>
<div id="root"></div>
<script type="text/javascript" ></script>
</body>
</html>
and views/index.jsx
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<h1>hello express</h1>,document.getElementById('root')
);
routers/index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
// res.render('index', { title: 'Express'}); this is the old line
res.render('index.html');
});
module.exports = router;
Try using sendFile instead of render in your routers/index.js file
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
// res.render('index', { title: 'Express'}); this is the old line
res.sendFile('index.html');
});
module.exports = router;

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>

Resources