express.js public folder not being recognised - javascript

I have developed a simple server in Node.js using Express and I have set the public folder to serve static files.
In my root index.js, I have the following code:
const express = require('express');
const app = express();
const http = require('http').Server(app);
const fs = require('fs');
app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
http.listen(3000, () => console.log('started server on *:3000'));
And the directory structure is:
root
|---index.js
|---package.json
|---public
| |---index.html
| |---cs
| | |---index.css
| |---js
| | |---index.js
In the index.html in the public folder, I have the following code:
<head>
<script src="js/index.js"></script>
<link rel="stylesheet" src="css/index.css" type="text/css" >
</head>
But no CSS is being rendered. How can I resolve this?

Replace src attribute in link tag to href. If this doesn't work then try below solution.
I'm considering your server is running on http://localhost:3000/
So update the url in src of your index.html in public folder by appending with the base url as I did below.
<head>
<script src="http://localhost:3000/js/index.js"></script>
<link rel="stylesheet" href="http://localhost:3000/css/index.css" type="text/css" >
</head>

Try changing this:
app.use(express.static(__dirname + '/public'));
To this:
app.use(express.static('public'));

Related

Node.javascript get on local host

I'm trying to follow a video but still can't get when I load by local host in the web browser.
I am get a console log of listening at 3000 but it seems that this line:
"app.use(express.static("/Users/name/Desktop/Weather App/public/app.html"));" is not working.
Any suggestions?
const express = require("express");
const app = express();
app.listen(3000, () => {
console.log("listening at 3000");
});
app.use(express.static("/Users/name/Desktop/Weather App/public/app.html"));
This the code Im using now.
server.js
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.sendFile(
"/Users/name/Desktop/Weather App/public/app.html"
// "/Users/name/Desktop/Weather App/public/style.css"
);
});
// serve any HTML files located in /Users/name/Desktop/Weather App/public
// app.use(express.static("/Users/name/Desktop/Weather App/public"));
app.listen(3000, () => {
console.log("listening at 3000");
});
app.html
<!DOCTYPE html>
<html>
<head>
<title>Weather App</title>
</head>
<body>
<h1>Weather App</h1>
<div id ="container">
<p>
Place: <span id = "places"></span><br/><br/>
Temperature: <span id="temperature"></span>&degC<br/><br/>
Feels like: <span id="feels"></span>&degC<br/><br/>
Minimum Temp: <span id="min"></span>&degC<br/><br/>
Maximum Temp: <span id="max"></span>&degC<br/><br/>
Humidty: <span id="hum"></span>&percnt;<br/>
</p>
<div>
<input id="inputter" type="text" ></input><br/><br/>
<button id="entButton">Click here for weather forecast</button><br/><br/>
<button id="geoEnter">Click here for fast weather</button><br/>
</div>
</div>
<div>
</div>
<script href="/Users/name/Desktop/Weather App/server.js"></script>
<script src="/Users/name/Desktop/Weather App/public/app.js" ></script>
<link href="/Users/name/Desktop/Weather App/public/style.css" rel="stylesheet" type="text/css"/>
</body>
</html>
any suggestions?
If you just want app.html to show when http://localhost:3000 is the URL, then you can do this:
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.sendFile("/Users/name/Desktop/Weather App/public/app.html");
});
app.listen(3000, () => {
console.log("listening at 3000");
});
If you have more files in /Users/name/Desktop/Weather App/public that you want to automatically serve to the client when requested, then you can add this:
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.sendFile("/Users/name/Desktop/Weather App/public/app.html");
});
// serve any HTML files located in /Users/name/Desktop/Weather App/public
app.use(express.static("/Users/name/Desktop/Weather App/public"));
app.listen(3000, () => {
console.log("listening at 3000");
});
So, if styles.css was located in /Users/name/Desktop/Weather App/public, then a URL for /styles.css would automatically serve the file /Users/name/Desktop/Weather App/public/styles.css.
Change the links in your app.html page to this:
<script src="/app.js"></script>
<link href="/style.css" rel="stylesheet" type="text/css"/>
The URLs in these tags need to be relative to the directory specified in your express.static() file and will usually start with a / so they are independent of the containing page URL.
The file system path supplied to express.static is too long.
express.static takes a directory path argument, not a file path. If the get request to the static server endpoint does not include a filename on the end (e.g. ".../app.html) express static middleware looks for a configurable default file name (initially set to index.html) for content to serve.
See also express.static documentation and in particular the index and extensions properties of the options object.

Can't load/find files on server with node.js, 404 error (not found)

I'm trying to load a script.js and a style.css file on the server. The index.html and index.js work fine, however, there seems to be an error when I try to load the style.css file and script.js file, which I use for backend.
GET http://localhost:4000/script.js net::ERR_ABORTED 404 (Not Found)
All my files are in the same directory, /public.
I already checked the CSS file, and it loads when I display the HTML file when it's not on the server.
This my index.js file:
const express = require('express');
const cors = require('cors');
const fs = require('fs')
const ytdl = require('ytdl-core');
const app = express();
const path = require('path')
app.use('/static', express.static(path.join(__dirname, 'public')))
app.use(cors());
app.listen(4000, () => {
console.log('Server works at port 4000');
});
app.get('/', function(req,res){
res.sendFile(__dirname + '/index.html');
});
app.get('/download', (req,res) => {
var URL = req.query.URL;
res.json({url:URL});
})
The HTML file:
<!DOCTYPE HTML>
<html lang="en">
<head>
<link href="/style.css" rel="stylesheet" type="text/css"/>
<meta charset="UTF-8">
<title>PyTube</title>
</head>
<body>
<h1>PyTube</h1>
<input type="url" name="yturl" class="URL-input" id="yturl" placeholder="https://www.youtube.com/watch?v=" required>
<button class="convert-button">Convert</button>
</body>
</html>
<script src="script.js"></script>
I've tried a bunch of things and trying things with __dirname and paths, but I can't find the issue or fix it.

Trying to serve static JS files Node.js, Err 404

I am trying to set up a simple node.js server to do some basic Socket.io work but when I try to serve my Static JS files I get this error:
GET https://somewebsitewithfiles.website net::ERR_ABORTED 404
Here is my server and local code:
Server:
var express = require('express');
var app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.sendFile(__dirname + '/HTML/index.html');
});
app.use(express.static('Static'))
http.listen(port, () => {
console.log(`Socket.IO server running at http://localhost:${port}/`);
})
Local:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="/Static/User.js"></script>
</body>
</html>
As you can see I have used the express static file command witch doesnt seem to be working . My file system consists of my project folder and inside that is my Server JS file. There is also folder in there called "Static" that has has my static files and a folder called HTML that has my index.html
any help appreciated. Thanks
app.use(express.static('Static'))
try putting this line above your '/' route
code:
var express = require('express');
var app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;
app.use(express.static('Static'))
app.get('/', (req, res) => {
res.sendFile(__dirname + '/HTML/index.html');
});
http.listen(port, () => {
console.log(`Socket.IO server running at http://localhost:${port}/`);
})
Edit:
<script src="/Static/User.js"></script>
You dont have to mention the 'static' in the src path.
Correct way:
<script src="/User.js"></script>

How to fix error Cannot GET with Node.js / Express

I have a class Server :
Server.js
const express = require('express');
class Server {
constructor() {
this.app = express();
this.app.get('/', function(req, res) {
res.send('Hello World');
})
}
start() {
this.app.listen(8080, function() {
console.log('MPS application is listening on port 8080 !')
});
}
}
module.exports = Server;
I start my server in app.js :
const Server = require('./server/Server');
const express = require('express');
const server = new Server();
server.start();
server.app.use('/client', express.static(__dirname + '/client'));
My html code :
index.html
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<title></title>
</head>
<body>
<div id="historique">
<button v-on:click="openHistorique">
Historique Proface
</button>
</div>
</body>
</html>
My index.js :
window.onload = function () {
var hist = new Vue({
el:'#historique',
methods: {
openHistorique: function() {
console.log("On clique");
document.location.href="../AffichageHistorique/index.php";
}
}
})
}
And the folder structure :
client
AffichageHistorique
index.php
js
index.js
index.html
server
Server.js
app.js
When I click on the button in index.html, I want to open index.php but i have the error Cannot GET /AffichageHistorique/index.php and I don't see how to fix the problem.
Here:
this.app.get('/', function(req, res) {
… you wrote a handler for what happens when the client tries to get /.
You haven't written one for /AffichageHistorique/index.php.
server.app.use('/client', express.static(__dirname + '/client'));
… comes close, but since your URL doesn't start with /client, it doesn't get hit.
Even if it did, it wouldn't execute the PHP.
The static module is for serving static files, not for executing PHP.
If you're using PHP, then consider using a server that PHP is designed to work with (like Apache HTTPD or Lighttpd).

node js res.render does not work, but res.send does

I am setting up the environment for a node js app. But the views/ejs files are not being rendered.
If i do:
app.get("/", function(req, res){
res.send('Hello');
});
it works.
But if i do:
app.get("/", function(req, res){
res.render("welcome");
});
it doesn't.
my app.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const indexRoutes = require("./routes/index");
const userRoutes = require("./routes/user");
const ejsLayouts = require("express-ejs-layouts");
const path = require("path");
mongoose.connect("mongodb://localhost/userAuth", function(err, res) {
if (err) throw err;
console.log("Connected to database");
});
//EJS
app.set('view engine','ejs');
app.use(ejsLayouts);
app.use(express.static(__dirname + '/public'));
app.set('views',path.join(__dirname+'/views'))
//ROUTES
app.use("/", indexRoutes);
app.use("/user", userRoutes);
app.listen(3000, function() {
console.log("server started");
});
my index.js file (userLogin/routes/index.js)
const express=require("express");
path = require('path');
router= express.Router();
router.get("/",function(req,res){
res.render("welcome");
});
module.exports = router;
my folder structure
userLogin
/..
/routes
/index.js
/views
/welcome.ejs
I have an h1 element olny in welcome.ejs file.
Looking at the code you provided, in index.js you are trying to render a view called check, when the only view you have is called welcome. Your paths and routes look to be correct, rendering the correct view should work.
app.engine('html', require('ejs').renderFile);
if u woudlike to render .html files
then
fs.readFile(path.resolve(__dirname + '/../public/views/logs.html'), 'utf-8', (err, content) => {
let renderedHtml = ejs.render(content, {'user': req.session.db}); //get redered HTML code
res.end(renderedHtml);
})
you should have views/layouts/layout.ejs file if you are using express-ejs-layouts npm
inside app.js :
const ejs =require('ejs');
const ejsLayouts = require("express-ejs-layouts");
app.set('view engine','ejs');
app.use(ejsLayouts);
app.set('layout', 'layouts/layout');
layout.ejs file has common layout that follow all files
if you are using bootstrap then your layout.ejs file would be like :
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<title></title>
</head>
<body>
<?- body ?>
</body>
</html>
so now other ejs pages will only have content to display
like welcome.ejs file is
<h1>Welcome Page</h1>

Categories

Resources