Heyo! I’d like to set up a 404 page such as when you go to https://mydomain.com/randomthings it sends you to the error page BUT if it’s a valid site such as /about.html it works… I tried the ExpressJS thing but, it’s showing an error for everything
My current code:
// server.js
// where your node app starts
// init project
var express = require('express');
var app = express();
// we've started you off with Express,
// but feel free to use whatever libs or frameworks you'd like through `package.json`.
// http://expressjs.com/en/starter/static-files.html
app.use(express.static('public'));
// http://expressjs.com/en/starter/basic-routing.html
app.get('/', function(request, response) {
response.sendFile(__dirname + '/index.html');
});
app.get('*', function(req, res){
res.sendFile(__dirname + '/404.html');
});
// listen for requests :)
var listener = app.listen(process.env.PORT, function() {
console.log('Your app is listening on port ' + listener.address().port);
});
for server.js
and package.json:
{
“//1”: “describes your app and its dependencies”,
“//2”: “https://docs.npmjs.com/files/package.json”,
“//3”: “updating this file will download and update your packages”,
“name”: “hello-express”,
“version”: “0.0.1”,
“description”: “A simple Node app built on Express, instantly up and running.”,
“main”: “server.js”,
“scripts”: {
“start”: “node server.js”
},
“dependencies”: {
“express”: “^4.17.1”
},
“engines”: {
“node”: “8.x”
},
“repository”: {
“url”: “https://glitch.com/edit/#!/hello-express”
},
“license”: “MIT”,
“keywords”: [
“node”,
“glitch”,
“express”
]
}
You have the code right. Do you not have the page you want?
nono, it’s working but, every page I go to, it shows Error 404 now
You need to add routing for every page you have. You already have the routing for the root domain (yourdomain.com). Also, you should put all your html files in a views
folder, and any js and css in a public
folderso for every page you have, you need to do something like this:
app.get("/page_url", (req, res) => {
res.sendFile(__dirname + "/views/page.html");
}
I hope this helps!
I forgot, static sites and routes don’t go well with eachother. You would need to map out every page in the JS file.