Cannot get correct static files after refreshing except index page - node.js

When I refresh page on index route (/) and login page (/login), it works fine.
However, my website gets error as I refresh on other routes, for example /user/123456.
Because no matter what the request is, the browser always gets HTML file.
Thus, both of the content in main.css and main.js are HTML, and the browser error.
I have already read the README of create-react-app.
Whether I use serve package ($serve -s build -p 80) or express, it will produce the strange bug.
Following is my server code:
//server.js
const express = require('express');
const path = require('path');
app.use(express.static(path.join(__dirname, 'build')));
app.get('/*', (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
const PORT = process.env.PORT || 80;
app.listen(PORT, () => {
console.log(`Production Express server running at localhost:${PORT}`);
});
Edit: I have figured out where caused the problem.
I created a new project, and compared it to mine. The path of static files in the new project is absolute, but in my project is relative.
As a result, I delete "homepage": "." in the package.json.
//package.json
{ ....
dependencies:{....},
....,
- "homepage": "."
}
Everything works as expected now. How am I careless...

I have figured out where caused the problem.
I created a new project, and compared it to mine. The path of static files in the new project is absolute, but in my project is relative.
As a result, I delete "homepage": "." in the package.json.
//package.json
{ ....
dependencies:{....},
....,
- "homepage": "."
}
Everything works as expected now. How am I careless...

If your route /user/** is defined after app.get('/*', ... it might not match because /* gets all the requests and returns you index.html.
Try without the * or declare the other routes before.

First, I thought you misunderstood the server part. In your case, you use serve as your server. This is a static server provided by [serve]. If you want to use your own server.js, you should run node server.js or node server.
I also did the same things with you and have no this issue. The followings are what I did:
create-react-app my-app
npm run build
sudo serve -s build -p 80 (sudo for port under 1024)
And I got the results:
/user/321
I guessed you might forget to build the script. You can try the followings:
remove build/ folder
run npm run build again
Advise: If you want to focus on front-end, you can just use [serve]. It will be easy for you to focus on what you need.

Related

express app is not sending index.html file to client

So my express app has a small Node server setup so it can serve up the index.html file when the home route '/' is hit. This is a requirement of using the App Services from Azure, there has to be this server.js file to tell the server how to serve up the client, and i had a previous implementation of this working, however i wanted to change my file structure. previously i had, the client React app in a folder client and the server.js in a folder server along with all of the conrtollers and routes. i've since moved the server API to its own application as there are other apps that depend on it. and i moved the client up one directory into the main directory. Everything was working fine till the other day when all of the sudden when you hit the home route / it will not serve up the index.html file. if you hit any other route it works, if you even hit a button linking back to the homepage, it works, but it wont serve up the app from the / and i cannot for the life of me figure out why, on my development server there are no errors in the console. and im most definitely targeting the correct directory and place for the index. but its like the server isnt reading the route to serve up.
if (process.env.NODE_ENV === 'production') {
console.log('running');
app.use(express.static(path.resolve(path.join(__dirname, 'build'))));
// no matter what route is hit, send the index.html file
app.get('*', (req, res) => {
res.sendFile(path.resolve(path.join(__dirname, 'build', 'index.html')));
});
} else {
app.get('/', (req, res) => {
res.send('API is running...');
});
}
So here im saying if the NODE_ENV is in production make the build folder static, and then whatever route is hit. (Note: i also tried this app.get with other route formats such as /* or / all have the same issues. however in my previous iteration when the client and server where deployed in the same location, /* is what i used.) The .env varialbes are setup correctly, as when the server is ran, itll console log running.. but even if i put a console log inside of the app.get() its like its never hit unless i access the route from something else first.
for example, if i place a console log inside of app.get that states hit whenever the route is hit, hitting / directly does nothing, but if i go to /login itll serve up the correct html on the client and console log hit in the terminal...
If you are having server files inside the client react app, then we are basically accessing file which are not inside our server file. So, we can serve static files using the following code:
const express = require("express");
const app = express(); // create express app
const path = require('path');
app.use(express.static(path.join(__dirname, "..", "build")));
app.use(express.static("build"));
app.listen(5000, () => {
console.log("server started on port 5000");
});
Now in your packages.json of the client react app change the name of start tag under scripts tag to start-client. Then add this following tag to the scripts tag:
"start":"npm run build && (cd server && npm start)",
Basically, this will build the react app and start the server.
It should look like this :
Also in the packages.json of your server add the following tag under script tag
"start":"node server.js"
So when you run the following command npm start it should look like this :

vercel not running build and instal commands and not creating Serverless functions

I am trying to move my application's API to Vercel. It is written in Typescript and uses Express.
The index.ts is located in <root>/src. The npm run build compiles it into <root>/dist directory. The file contains the following:
const app = express();
app.use((req: Request, res: Response, next: NextFunction) => {
//blah, blah, there is a lot going on here
})
app.use('/', common);
//... other app.use(s)
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on ${port}, http://localhost:${port}`));
module.exports = app;
I've got the following in the vercel.json file which is located in the root directory where the package.json also is:
{
"version": 2,
"installCommand": "npm install",
"buildCommand": "npm run build",
"outputDirectory": "dist",
"builds": [
{
"src": "dist/index.js",
"use": "#vercel/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "dist/index.js"
}
]
}
When locally I run npm run build, then vercel dev --listen 5000 I get Ready! Available at http://localhost:5000 and can go to http://localhost:5000/ping and get a response.
Now I commit the files to git, the deployment runs, but judging by the logs the npm install and npm run build commands are not running. No functions are created my /ping endpoint returns "Page not found".
Here is the deployment log:
This is what Build & Development Settings look like (the Root Directory is left blank):
I followed several recommendations I found online and according to them everything should work. I probably miss some setting somewhere. What is it?
If more information is needed, please let me know, I'll update my question.
Thank you.
--- UPDATE ---
I have set the Root Directory to src and checked the "Include source files outside of the Root Directory in the Build Step" checkbox. Now the npm install and npm run build are executing. As you can see some static files are deployed, but there are still no serverless functions and my /ping route returns 404 and "home" page, i.e. / route returns the content of the index.js file. In addition the local is not working either anymore, also returning 404 now.
Without that checkbox I was getting
Warning: The vercel.json file should exist inside the provided root directory
and still no install or build running.
Also worth noting that I had to change my tsconfig.json to have "outDir": "src/dist" instead of "outDir": "dist", otherwise I was getting
Error: No Output Directory named "dist" found after the Build completed. You can configure the Output Directory in your Project Settings.
Removed the Root directory and back to square one, no npm commands running but local is working with / route returning Cannot GET / and /ping returning correct response.
For everyone out there who's looking for an answer, maybe this will help you.
In my case, what I needed is to create a folder, called api in my src folder, i.e. the folder that is specified as Root Directory in Build & Development Settings in Vercel. Within this directory, each serverless function needs a file named the same as the path of the route. For example, the file named "my-route.js" will be accessible via https://my-app-name.vercel.com/api/my-route.
All this file needs is an import of index.js file and module.exports. For example:
import app from '../index';
module.exports = app;
The index.js should also live the Root and contain your express setup.
If you want to have dynamic path parameters, the files' names in the api directory should be wrapped in square brakets, like [my-param.js]. You can also have sub-directories in the api foler.
Here are a few links that helped me figure this out:
https://dev.to/andrewbaisden/how-to-deploy-a-node-express-app-to-vercel-2aa
https://medium.com/geekculture/deploy-express-project-with-multiple-routes-to-vercel-as-multiple-serverless-functions-567c6ea9eb36
https://ryanccn.dev/posts/vercel-framework/#path-segments
No changes were needed in my existing Express setup and routes files.
Hope this will help someone. Took me quite a while to figure it all out :)

Error trying to render the index.html that ng build generates with node and express

I want to deploy an application that I perform with the MEAN stack on Heroku, but I encounter 1 problem.
I have this folder structure, my node server, with a public folder, where is the dist / fronted folder and all the files generated by Angular's ng build --prod, it works when I start the server and browse normally, but if I refresh the page or write a route myself, I get these errors:
Errores
Sorry for my English.
If your are building a MEAN stack, you probably have a server.js or index.js or app.js as an entry point to your application. An SPA by definition manages all the routes within the router configuration. But if you try to refresh or type a route yourself, it is like you were trying to access that folder on the server (ex: www.mywebsite.com/about, here the folder about might not exist on the server, it is just known by your Angular app)
My suggestion is that you try to add this fix to the app.js (or server.js or app.js) file, so all unexisting routes or refresh go back to your index.html:
// Check your port is correctly set:
const port = process.env.PORT || 8080;
// Is saying express to put everything on the dist folder under root directory
// Check the folder to fit your project architecture
app.use(express.static(__dirname + "/dist"));
// RegEx saying "capture all routes typen directly into the browser"
app.get(/.*/, function(req, res) {
// Because it is a SPA, all unknown routes will redirect to index.html
res.sendFile(__dirname + "/dist/index.html");
});
app.listen(port);
This guy shows full deploy on Heroku with Angular: https://www.youtube.com/watch?v=cBfcbb07Tqk
Hope it works for you!

express server starting react client

Until now, I have been using create-react-app for my projects, with the express-server and the react client each in their own folders.
However, I am now trying to avoid create-react-app in order to really understand how everything work under the hood. I am reading an Hacker Noon article that explains how to setup react with typescript and webpack. In this article they also have the express server at the root of the client which compiles everything itself:
const path = require('path'),
express = require('express'),
webpack = require('webpack'),
webpackConfig = require('./webpack.config.js'),
app = express(),
port = process.env.PORT || 3000;
app.listen(port, () => { console.log(`App is listening on port ${port}`) });
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'dist', 'index.html'));
});
let compiler = webpack(webpackConfig);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true, publicPath: webpackConfig.output.publicPath, stats: { colors: true }
}));
app.use(require('webpack-hot-middleware')(compiler));
app.use(express.static(path.resolve(__dirname, 'dist')));
In the end, the start command looks like it:
"start": "npm run build && node server.js"
So I assume the client and the server start on the same port.
Why would you do such a thing? Are there any pros and cons?
It is true that this will allow your development to happen using the same server as express and that web pack will continuously update your dist/index.html file with whatever updates you make to your file. There's not too much of a disadvantage to this as this is just for development. But typically on prod you'll have a single built file that you will serve. And it will not web pack-dev-middleware to be running. Once you've built your server. For the purposes of production it might be possible that you'll only need static assets. But typically, even the server which serves mostly client files will potentially need a server if you want to do server side rendering and/or code splitting.
The command: "npm run build && node server.js" will run the bash/cmd commands into the terminal. npm run build is one step because of the use of && it will if that command succeeds, run the next command which is node server.js which is a strange command I would probably run node ./ (and put the server as index.js) or at least just write node server.
What I'd prefer to see in your package.json:
"start": "yarn build && node ./"
That would be possible if you mv server.js index.js (and npm i -g yarn).
Another thing to note, and look into is what the build step does.
Further Explanation:
The command runs the build step so check what your "build": key runs in your package.json.
This command will probably not exit with the code 1 (any exit code of a terminal process that is above 0 will result in an error and will not pass the &&).
Presumably, the build process described in the package.json will take all the javascript and CSS files and put them into the index.html file which will then be sent to the client side whenever someone access the '/' path.
After that succeeds, it will start the server that you put the code to above.
res.sendFile(path.resolve(__dirname, 'dist', 'index.html'));
will happen if anybody comes across the '/' path.

NOde.js/Express App can't find some node_modules

I use several Node/Express modules in my app, and everything works fine for every module as long as I do const module = require('module');. I don't need to define a static path for these modules as app.use(express.static(path.join(__dirname, 'public')));.
However, for the sweetalert module, if I define in my layout.pug (base pug file) script(src="/node_modules/sweetalert/dist/sweetalert.min.js"), I get a 404 Error (not found) unless I include in app.js the following static path: app.use("/node_modules", express.static(__dirname + "/node_modules"));.
My question is: is this the normal behaviour or is it something I'm not doing right? (I'm kinda confused why I have to define a static path just for one of several modules I use.
Here's whats going on:
app.use(express.static(path.join(__dirname, 'public'))); is declaring that the public directory is accessible to the browser. You should put all your front end resources in that folder. This will help separate what can be accessed from the server and what can be accessed from the client.
When you reference script(src="/node_modules/sweetalert/dist/sweetalert.min.js") the browser throws a 404 because that file is not located in the public directory, therefore off limits to the browser.
Adding this line app.use("/node_modules", express.static(__dirname + "/node_modules")); "fixes" your issue but now exposes all your node_modules to the browser. This probably isn't a good idea and I'm sure a security expert could elaborate why this shouldn't be done.
How I would resolve this issue: Go through your .pug code and look at any resources your front end requires. Then copy them over to the public folder and fix your references to use the copy of the resource.
Here's an example of a script I use to move resources from the node_module directory to a public/assets directory:
build.js:
const path = require('path');
var fs = require('fs');
const ASSETS = [
'jquery/dist/jquery.min.js',
'sweetalert/dist/sweetalert.min.js'
];
if (!fs.existsSync('./public/assets')){
fs.mkdirSync('./public/assets');
}
ASSETS.map(asset => {
let filename = asset.substring(asset.lastIndexOf("/") + 1);
let from = path.resolve(__dirname, `./node_modules/${asset}`)
let to = path.resolve(__dirname, `./public/assets/${filename}`)
if (fs.existsSync(from)) {
fs.createReadStream(from).pipe(fs.createWriteStream(to));
} else {
console.log(`${from} does not exist.\nUpdate the build.js script with the correct file paths.`)
process.exit(1)
}
});
then I update my package.json to include this in the scripts:
package.json:
"scripts": {
"build": "node ./build.js || true",
"start": "node ./bin/www"
}
then in any of my views pages I reference the resource by using the new path
random.pug:
script(src="/assets/jquery.min.js")
script(src="/assets/sweetalert.min.js")
Finally before you deploy your app you now must run the following command:
npm run build then npm start
You will only need to run the build command if your front end resources change. So if you only ever use sweetalert.min.js you will only need to run the build the first time you run your app. If later on you add another resource aNewResource.js you will need to update the build.js file and run npm run build again.

Resources