Cannot access static files from URL in express application - html

I have built a basic express app as below -
index.js
const express = require("express");
const app = express();
app.use(express.static(__dirname + "public"));
app.get("/", (req, res) => {
res.json({ message: "Hello World!" });
});
app.listen(3000, () => {
console.log("Server is running on port 3000");
});
I want to serve static files directly from the browser URL, and according to this express doc page it is indeed possible.
Accordingly, I have created a folder called public in the root folder and have kept two files in it - one demo.html, and one image.jpg. My folder structure -
express-app
|- index.js
|- public
|- image.jpg
|- demo.html
However, when I try to access http://localhost:3000/demo.html or http://localhost:3000/image.jpg, I get a Cannot GET error.
Can anybody please tell me why it isn't working?

app.use(express.static(__dirname + "public"));
__dirname does not include a trailing slash.
__dirname + "public" will give you something like: /home/me/express-apppublic — a directory that doesn't exist.
The documentation you link to shows the use of path.join to include the correct directory separator for your operating system.
const path = require('path')
app.use('/static', express.static(path.join(__dirname, 'public')))
Don't omit that part!

Related

Showing HTML file in Node js Application

I am new on Node.js and I have app.js file like:
const express = require('express');
const app = express();
const port = 8080;
app.get('/', (req, res) => res.send('Hello World'));
app.listen(port);
console.log(`App running on http://localhost:${port}`);
I also have index.html file in the same folder with app.js. Here there is a HTML5 website.
When I run the project I can see Hello World text in browser, How can I show this HTML file from my app.js so when I deploy it, it should show me responsive HTML file instead of Hello World?
I tried
app.get('/',function(req,res) {
res.sendFile('index.html');
});
But didn't see a difference.
To make your code example work you'll need to specify an absolute path, try using this:
res.sendFile(__dirname + "/index.html");
Another way would be to use EJS (https://ejs.co/)
In your example, you could do the following:
Install EJS:
npm install ejs
Set the View Engine to EJS:
app.set('view engine', 'ejs')
- Move your index.html file to a folder called "views" and also rename the file to index.ejs
views/index.ejs
In your app.get() handler, use:
res.render('index')
Final Result:
const express = require("express");
const app = express();
app.set("view engine", "ejs");
const port = 8080;
app.get("/", (req, res) => {
res.render("index");
});
app.listen(port, () => {
console.log(`App running on http://localhost:${port}`);
});
(note: I also moved your console.log to inside app.listen)
I found this on another stack overflow question, it should work
fs.readFile(__dirname + '/views/test.html', 'utf8', function(err, text){
res.send(text);
});

GET to CSS returns 404

So I recently moved my website from a single-page website to an express server. Now I changed the file paths, but I cannot get my css and js files to load.
As seen in the developer console, the GET request to https://<website>.com/public/css/main.css returns a 404.
This is the css link:
<link rel="stylesheet" type="text/css" href="../public/css/main.css">
This is my server:
const express = require('express');
const app = express();
const getpages = require('./router/getpages.js');
app.use('/', getpages);
app.use(express.static('public'));
// 404's
app.use((req, res) => {
res.status(404).send('Page not found or non-existant.<br><br>Home');
});
app.listen(3000, console.log('Running on port 3000'));
This is ./router/getpages.js:
const router = require('express').Router();
const path = require('path');
router.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '../views/', 'index.html'));
})
module.exports = router;
This is the file structure:
Note, I could not find any other questions that helped me, before this is marked as a dupe again.
As can be seen from the documentation, you should not have public in the route
https://<website>.com/css/main.css should work as expected.
refer : https://expressjs.com/en/starter/static-files.html
For example, use the following code to serve images, CSS files, and
JavaScript files in a directory named public:
app.use(express.static('public'))
Now, you can load the files that are
in the public directory:
eg : http://localhost:3000/images/kitten.jpg
Express looks up the files relative to the static directory, so the
name of the static directory is not part of the URL.

Adding another page other than index.html

I started my own VPS, and started a web server using NGINX. I have an index.html. How do I create other pages, like an about page, and having it live at www.my-domain-name.com/about/
Does this mean I have to edit my app.js file, if so, how?
Amendment: I added Lazar's suggested amendment to the Express code to get the about.html.
'use strict';
const express = require("express");
const app = express();
// Static css/js files
app.use('/static', express.static('./dist'));
app.get("/", function(req, res) {
res.sendFile( __dirname + '/index.html');
});
app.get("/about", function(req, res) {
res.sendFile( __dirname + '/about.html');
});
const port = 3001;
// Start server
app.listen(port, function() {
console.log("Listening on " + port);
});
In index.html, the link to the about page is:
About me.
Both /about and /about.html don't currently work and receive the error message: Cannot GET /about.html
Edit: I am using forever, so I had to forever restartall
Considering that you are using express, for every created route, create appropriate html page - or use some other thing, like handlebars, etc.
For example you created index.html for "/" route.
For about us route, create aboutus.html
app.get("/aboutus", function(req, res) {
res.sendFile( __dirname + '/aboutus.html');
});
and so on...
For more info check their official web page: https://expressjs.com/

How to send React.js files with express .senfFile?

I am using create-react-app.
When you go to localhost:3001/test - it does serve up the HTML. But all you see is an empty page because nothing in the id "root" is rendered.
This is the code I have in my server:
app.get('/test', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
})
and my HTML is close to this:
<body>
<div id="root"></div>
</body>
You have to set the location of the static files. For example if you use environment variable.
if(process.env.ENV === 'prod'){
app.use(express.static('client/build'));
const path = require('path');
app.get('/test', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
})
}
Also, do make sure to run npm run build in order to create all the necessary files for deployment.
Based on the few details provided, I'll give a checklist
1- Make sure you have root in this part of your code
ReactDOM.render(<YourApp />, document.getElementById('root'));
2- In your console, do you have any error messages similar to this?
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
...Then your are just simply not receiving your data from the server because of CORS issues. Use this: CORS
3- Double check that your server that does the res.sendFile is running properly, check your terminal to check for errors like "file not found" or similar issues.
4- This works (I just tried it), try it in the same directory as your current server. Paste the code in testNode.js and run node testNode.js then visit http://localhost:3003/test
const express = require('express')
const app = express()
const port = 3003
app.get('/test', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
})
app.get('/', (request, response) => {
response.send('Hello from Express!')
})
app.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})
5- Is the public/ folder readable? Does it have the right permissions? Try a chmod -R 777 public/ (change it back later)

Setting up Node.js with express.js on my 'portfolio' site

I'm completely new to node.js but i'm trying to implement it on my personal site so that I start learning it. I have the node server running but i'm trying to set up the routing using express.js . All my files are typical static files .html, .js, .cs, .png , etc. Currently, the route gives me my index page on the 'home' page which is goo. If I attempt to navigate to the index of another diectory, I just get the 404 error page. My file structure is like this:
Server.js
package.json
node_modules
-- views (Folder)
-index.html (File in views)
--Projects (Folder in Views)
-index.html (File in Projects)
my Server.js looks like
var express = require("express");
var app = express();
var router = express.Router();
var path = __dirname + '/views/';
router.use(function (req, res, next) {
console.log("/" + req.method);
next();
});
router.get("/", function (req, res) {
res.sendFile(path + "index.html");
});
router.get("/Projects", function (req, res) {
res.sendFile(path + "Projects/index.html");
});
app.use("/", router);
/*app.use("*", function (req, res) {
res.sendFile(path + "404.html");
});*/
app.listen(3000, function () {
console.log("Live at Port 3000");
});
I've looked for the past ~18 hours at various resources and i'm just missing something i'm sure. My current idea of the issue is the navigation links in the html, however I've attempted changing those with no progress.
If you have only public file (like html, css, ..) you can put everything on a /public folder and add this instead of a router.
app.use(express.static('public'))
Doc: https://expressjs.com/en/starter/static-files.html
Every file will be accessible:
/public/my-folder/my-file.png > www.my-dmain.com/my-folder/my-file.png