node.js - Static files CSS / JS not working in express - javascript

I Understand many people have asked the same question but i just can't get this to work for me at all.
I am trying to make a socket.IO application and are following the tutorials but just can't get CSS and JS to be loaded to the page. The application just always sends the html page.
My folder structure.
./server.js
./public
/css
/styles.css
/js
/client.js
/index.html
My Server.js file contains:
var express = require('express');
const socketIO = require('socket.io');
const path = require('path');
const PORT = process.env.PORT || 3000;
const INDEX = path.join(__dirname, '/public/index.html');
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
const server = express()
.use((req, res) => res.sendFile(INDEX) )
.listen(PORT, () => console.log(`Listening on ${ PORT }`));
const io = socketIO(server);
And in my index.html file I call the css and js like this:
<link rel="stylesheet" type="text/css" href="/css/styles.css" />
<script src="/js/client.js"></script>

Why use two express variables app and server
Try the following
const socketIO = require('socket.io');
const path = require('path');
const INDEX = path.join(__dirname, '/public/index.html');
const PORT = process.env.PORT || 3000;
var express = require('express');
const app = express()
.get('/', function (req, res) {res.sendFile(INDEX)})
.use(express.static(__dirname + '/public'))
.listen(PORT, () => console.log(`Listening on ${ PORT }`));
const io = socketIO(app);

This will work:
const express = require('express');
const app = express();
const http = require('http').Server(app);
const socketIO = require('socket.io')(http);
const PORT = process.env.PORT || 3000;
app.use(express.static(__dirname + '/public'));
http.listen(PORT, () => console.log(`Listening on ${ PORT }`));
Your code doesn't work because .use((req, res) => res.sendFile(INDEX)) always sends index.html, to any request from the client.

Related

How can I access the files used in a HTML file on a website with Node.JS

I am having a problem with Node.JS.
I'm trying to upload a HTML file with Node.JS (the HTML file has links to JS, JSON and CSS files) but when I turn on the server and look at the page, only what was in the HTML is written, which means there is no CSS and no JS which were working properly before I implemented the server.
Can anyone help me?
Here's the Node.JS code:
const express = require('express');
const app = express();
const port = 3000;
app.use(express.static('project-folder'));
app.get('/', function(req, res){
res.sendFile('website.html', { root: __dirname });
});
app.listen(port, function(){
console.log("server is up");
});
If your folder structure looks like this:
project-folder
|-website
| |-style.css
| |-script.js
|-website.html
|-server.js
then the code should look like this:
const express = require('express');
const app = express();
const port = 3000;
const path = require('path');
app.use(express.static(path.join(__dirname, 'website')));
app.get('/', function(req, res){
res.sendFile('website.html', { root: __dirname });
});
app.listen(port, function(){
console.log("server is up");
});
if it's like this:
project-folder
|-website
| |-style.css
| |-script.js
| |-website.html
|-server.js
then the code should look like this:
const express = require('express');
const app = express();
const port = 3000;
const path = require('path');
app.use(express.static(path.join(__dirname, 'website')));
app.get('/', function(req, res){
res.sendFile('website.html', { root: path.join(__dirname, 'website') });
});
app.listen(port, function(){
console.log("server is up");
});
Mind the path module that is required at the top

routing error Cannot Get /api/name student activity

I'm trying to recreate a Note Taking App using Express. My code follows the instructor's example but when I deploy it and try to add a new note I get the error cannot get/api/name...I am not sure what I am doing wrong.
enter code here
const fs = require('fs');
const path = require ('path');
const express = require('express');
const dbJson = require('./db/db.json')
const {v1 : uuidv1} = require('uuid');
const PORT = process.env.PORT || 3001;
const app = express();
app.use(express.urlencoded({extended: true}));
app.use(express.json());
app.use(express.static("public"));
app.get('/notes', (req, res) => {
res.sendFile(path.join(__dirname, './public/notes.html'));
});
app.get('/api/notes', (req,res) => {
const dataNotes = fs.readFileSync(path.join(__dirname, './db/db.json'), "utf-8");
const parseNotes = JSON.parse(dataNotes);
res.json(parseNotes);
});
Add at the end: app.listen(PORT);
That will work. The problem was that you didn't start the server

Socket.io Page Loading Forever

Note - I'm using Pug to render my pages.
My page, when including the script(src="/socket.io/socket.io.js"), does not stop loading.
Here's the relevant content from my app.js.
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
All packages are installed correctly.
In my head tag:
script(src="/socket.io/socket.io.js")
script.
var socket = io();
Yet, my page does not stop loading. What have I done wrong here?
Update:
app.js
const path = require('path');
const express = require('express');
const morgan = require('morgan');
const cookieParser = require('cookie-parser');
const AppError = require('./utils/appError');
const globalErrorHandler = require('./controllers/errorController');
const userRouter = require('./routes/userRoutes');
const viewRouter = require('./routes/viewRoutes');
const projectRouter = require('./routes/projectRoutes');
const app = express();
app.set('view engine', 'pug')
app.set('views', path.join(__dirname, 'views'));
//MIDDLEWARES
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
}
app.use(express.urlencoded({extended: true}));
app.use(express.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use((req, res, next) => {
req.requestTime = new Date().toISOString();
next();
});
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'overview'));
})
//ROUTES
app.use('/', viewRouter);
app.use('/api/1/users', userRouter);
app.use('/api/1/projects', projectRouter)
app.all('*', (req, res, next) => {
next(new AppError(`Can't find ${req.originalUrl}.`, 404));
});
app.use(globalErrorHandler);
module.exports = app;
server.js (run by node)
const mongoose = require('mongoose');
const dotenv = require('dotenv');
// mongoose.set('debug',true);
dotenv.config({path: './config.env'})
const app = require('./app');
const DB = process.env.DB.replace('<PASSWORD>', process.env.DBPASS);
mongoose.connect(DB, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
}).then(con => {console.log('🔗 Connected.')})
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`📈 Running on ${port}.`)
});
const http = require('http').Server(app);
const io = require('socket.io')(http);
io.on('connection', socket => {
socket.on('greeting', msg => {
console.log(msg);
})
});
http.listen(80);
Now that you've shown your code, this part is wrong:
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`📈 Running on ${port}.`)
});
const http = require('http').Server(app);
const io = require('socket.io')(http);
You are creating two separate servers there and binding socket.io to the one that isn't running. Change that above code to this:
const port = process.env.PORT || 3000;
const server = app.listen(port, () => {
console.log(`📈 Running on ${port}.`)
});
const io = require('socket.io')(server);
Earlier attempt to help before OP had shown their actual code.
My guess is that something is messed up in your environment or something is wedged in your OS or something is blocking some requests. To rule things in or out, I would suggest you try this simple app which works just fine for me:
// app.js
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const path = require('path');
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "temp.html"));
});
io.on('connection', socket => {
socket.on("greeting", msg => {
console.log(msg);
});
});
server.listen(80);
and the HTML file temp.html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="/socket.io/socket.io.js"></script>
<style>
</style>
</head>
<body>
<button id="myButton">Press Me</button>
<script>
const socket = io();
document.getElementById("myButton").addEventListener("click", () => {
socket.emit("greeting", "hi from client");
});
</script>
</body>
</html>
You put these two files in the same project and you have the server-side socket.io library installed in that project (it should be in node_modules per a normal installation).
Start the server with node app.js in a way that has a server console that you can see output from. Then, from a browser on the same computer, go to http://localhost. It should load a web page with a single button on it. Press that button. You should see a message in the server console that says hi from client each time you press that button.
If this is working, then we would need to see all your project code to see what's wrong with your actual project.
If this isn't working, then we need to know what errors you get. You can try moving this project to a different port in case you have something blocking some things on a particular port. You can reboot your computer in case something in the networking or file system is wedged.

Routes navigation is not working in NodeJs

I am using router in my NodeJs app.When I am trying to navigate it is unable to navigate to the given page.
Register.js is placed in routes folder and server.js is placed in parent directory.
Here is my code:
Server.js
const express = require('express');
const app = express();
app.set('view engine','ejs');
app.use(require('./routes/register'));
const port = process.env.PORT || 3000;
app.listen(port, (req,res) => {
console.log("Server is running at:", +port);
});
Register.js
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
var app = express();
router.use(bodyParser.json);
router.use(bodyParser.urlencoded({extended:true}));
router.get('/users', (req,res) => {
console.log('Hello there');
});
module.exports = router;
Now when I run this code and go to localhost:3000/users nothing happens and not even error shows in console.
Please let me know what I am doing wrong in above code.
Use router.use(bodyParser.json()); in register.js.
You have used body-parser at wrong place. Also you should initiate those with express instances always.
Also check your file name you have imported. Reigster -> register
Updated code:
Server.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.set('view engine','ejs');
app.use(require('./Register'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
const port = process.env.PORT || 3000;
app.listen(port, (req,res) => {
console.log("Server is running at:", +port);
});
Register.js
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
router.get('/users', (req,res) => {
console.log('Hello there');
res.sendStatus(200)
});
module.exports = router;

Nodejs middleware in two files

Hi I have these two files, and trying to call index.js from server.js which works fine and is printing 'on the other side of the code' but it is not going inside the app.get function. Please advise what I am doing wrong
Server.js
const express = require("express")
const bodyParser = require("body-parser")
const app = express()
var routes = require('./api/index.js')
const PORT = process.env.PORT || 3000
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use('/t', require('./api/index')(app))
var server = app.listen(PORT, function (){
var host = server.address().address
var port = server.address().port
console.log('Middle ware started on address http://%s:%s',host,port)
})
index.js
const express = require('express')
module.exports = function(app) {
console.log('we are in other part of code')
app.get('/',function(req,res){
console.log('we are there')
console.log(res)
})
}
You should use express Router class to create modular route handlers:
Server.js
const express = require("express")
const bodyParser = require("body-parser")
const app = express()
var routes = require('./api/index.js')
const PORT = process.env.PORT || 3000
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use('/t', routes)
app.listen(PORT, function (){
var host = server.address().address
var port = server.address().port
console.log('Middle ware started on address http://%s:%s',host,port)
})
index.js
const express = require('express')
const router = express.Router()
router.get('/',function(req,res){
console.log('we are there')
res.send('successfully get /t')
})
module.exports = router;
Your approach is not right try this way
server.js
const express = require("express")
const bodyParser = require("body-parser")
const app = express();
const PORT = process.env.PORT || 3000
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use('/t', require('./api/index.js'));
var server = app.listen(PORT, function (){
var host = server.address().address
var port = server.address().port
console.log('Middle ware started on address http://%s:%s',host,port)
})
index.js
const express = require('express');
router=express.Router();
router.get('/',function(req,res){
console.log('we are there')
console.log(res)
res.send('success')
});
module.exports=router;
Server.js
const express = require("express")
const bodyParser = require("body-parser")
const app = express()
var routes = require('./api/index.js')(app) // Pass the app
const PORT = process.env.PORT || 3000
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use('/t', routes) // change this to routes
var server = app.listen(PORT, function (){ var host = server.address().address var port = server.address().port
console.log('Middle ware started on address http://%s:%s',host,port) })
index.js
const express = require('express')
module.exports = function(app) {
console.log('we are in other part of code')
app.get('/',function(req,res){
console.log('we are there')
console.log(res)
res.json({success : true});
})
}

Categories

Resources