This question already has an answer here:
Link index.html client.js and server.js
(1 answer)
Closed 1 year ago.
When I run my HTML file on a local server written in node.js, the CSS file that I linked in my HMTL file does not work.
my javascript code
const http=require('http');
const fs=require('fs');
http.createServer(function(req,res){
fs.readFile("index.html",(error,data)=>{
res.writeHead(200,{'Content-Type':'text/html'});
res.write(data);
return res.end();
})
}).listen(8080);
my HTML file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type=text/css href="./css/desktop.css">
<title>CODESTER-TrackYourProgress</title>
</head>
<body>
...
</body>
</html>
my CSS file is in folder css, and name is called desktop.css.
Express module solved the problem
you can use
const express = require('express');
const app = express();
app.use(express.static('folder containing your static files'));
//statics files are css,photos etc
You could try something like this:
const http=require('http');
const fs=require('fs');
http.createServer(function(req,res){
const { method, url } = req;
const surl = new URL(url, 'url the server is running on');
if (method == 'GET' && surl.pathname == '/index.html') {
fs.readFile("index.html",(error,data)=>{
res.writeHead(200,{'Content-Type':'text/html'});
res.write(data);
return res.end();
})
}
if (method == 'GET' && surl.pathname == '/css/desktop.css') {
fs.readFile("/path/to/css/desktop.css",(error,data)=>{
res.writeHead(200,{'Content-Type':'text/css'});
res.write(data);
return res.end();
})
}
}).listen(8080);
Be sure to replace /path/to/css/desktop.css with your actual path to the file and 'url the server is running on' with a valid url that the server is running on eg. http://127.0.0.1/
Related
I don't understand where my code goes wrong. Please help me. Whenever I run this code (nodemon app.js in terminal) I got error(error:- can't get) in the browser. Thank you in advance for helping me.
app.js code:-
const express =require("express")
const bodyParser=require("body-parser");
const app=express();
app.set("view engine","ejs");
app.set("/",function (req,res) {
var today=new Date();
var day="";
if(today.getDay()==6||today.getDay()==0)
day="weekend";
else
day="weekday";
res.render("todo", { kindofDay: day});
});
app.listen(3000,function() {
console.log('server is starting...');
});
todo.ejs code:-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ejs day list</title>
</head>
<body>
<h1>It's a <%= kindofDay %> !</h1>
</body>
</html>
You have to use app.get
app.get("/",function (req,res) {
var today=new Date();
var day="";
if(today.getDay()==6||today.getDay()==0)
day="weekend";
else
day="weekday";
res.render("todo", { kindofDay: day});
});
I have a simple pure node.js server which sends back html page on request.
In my html page i have connected js file.
When i make a request i get on response the html page but no the js file.
In my console i got an error.
Uncaught SyntaxError: Unexpected token '<'
my node.js server file:
const http = require('http');
const fs = require('fs');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html', });
fs.readFile('index.html', function(err, data){
if(err){
return console.log(err);
}
res.end(data);
});
}).listen(8080);
console.log('Server is running on Port: 8080');
my html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>here</h1>
<script src="./app.js"></script>
</body>
</html>
Any suggestions how to send multiple files on request with pure js ?
You're currently serving all requests with index.html, so when the browser requests app.js you do not get the script, but the index-page instead, hence the error.
You'd need to check the request path in your server's callback and then send the correct file (see this for a more detailed example):
http.createServer(function (req, res) {
if (req.path === '/app.js') {
// read app.js file and send it to the client
} else {
res.writeHead(200, {'Content-Type': 'text/html', });
fs.readFile('index.html', function(err, data){
if(err){
return console.log(err);
}
res.end(data);
});
}).listen(8080);
You see that this is pretty cumbersome, so I highly recommend using a framework like express (it provides a middleware to serve static files out of the box) to do this.
My folder structure is :
APP
-public
main.js
-views
index.html
index.js
I am trying to serve the static file to express server but its not working. The code for this in my index.js file is:
const express = require('express'),
app = express();
app.use(express.static(__dirname+'/public'));
I have also tried using path.join syntax
In my index.html file in the views folder , I am using the src tag as 'main.js'
<script type="text/javascript" src="main.js"></script>
I get the error net::ERR_FILE_NOT_FOUND.
I can also see that path src is referring to is wrong.
It is looking for main.js file in views directory instead of looking in public directory.
I have looked at other answers. I understand the syntax theoretically but am not able to find what I am doing wrong
Please point out the issue in my code. Thanks
Here is a working example:
index.js:
const express = require('express');
const path = require('path');
const app = express();
const port = 3000;
app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, './views/index.html'));
});
app.listen(port, () => console.log(`server is listening on port ${port}`));
./public/main.js:
window.onload = function() {
console.log('onload');
};
./views/index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script type="text/javascript" src="main.js"></script>
</head>
<body>
This is template
</body>
</html>
I'm going crazy over this...
I have this simple NodeJS server running - it serves the ./start.html file fine, but the CSS-file is not loaded.
My folder structure looks like this:
/public/css/styles.css
/interface.js (the Node-file)
/start.html
Node is running this code:
const app = express();
const hostname = '127.0.0.1';
const port = 3000;
let serials;
app.use(express.static('public'));
// Make these folders accessible by our HTML-files
app.use('/css', express.static(__dirname + '/public/css'));
//app.use('/js', express.static(__dirname + '/public/js')); // Not used at the moment
//app.use('/images', express.static(__dirname + '/public/images')); // Not used at the moment
app.get('/start', (req, res) => {
const fs = require('fs');
var content;
// We load the file asynchronously and pass on the content to the screen when loaded.
fs.readFile('./start.html', function read(err, data) {
if (err) {
throw err;
}
res.writeHead(200, { 'Content-Type': 'text/html', 'Content-Length': data.length, 'Expires': new Date().toUTCString()});
res.end(data);
});
});
The start.html file looks like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>start</title>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<link href="css/styles.css" rel="stylesheet" type="/text/css">
<script type="text/javascript">
$(document).ready(function() {
etc...
When accessed, using localhost:3000/start, it only shows the HTML-code.
When opening localhost:3000/css/styles.css it displays the stylesheet just fine.
The browser console also does not show any CSS-file loaded.
Any suggestions, please?
Simple mistake: the CSS linkage had a "/text/css" instead of "text/css" and not an error in the JS after all. Now it works perfectly.
I have a nodejs app that acts as a remote control for Cmus music player. It uses a route for each function ie /play /next etc. This works fine, but with each button click I must call res.redirect("index.html") which obviously causes the page to reload. How can I perform this so that each button click is still able to send the command to the server but not reload the page?
server.js
var express = require('express');
var app = express();
var path = require('path');
var exec = require('child_process').exec;
var Commands = require('./commands.js');
var child;
app.use(express.static(__dirname + '/public'));
//Routes
app.get('/', function (req, res){
res.sendFile(path.join(__dirname + '/index.html'));
});
app.get('/play', function(req, res){
// console.log(req);
handleCommand(Commands.PAUSE);
res.redirect("index.html");
});
var server = app.listen(8080, function () {
console.log("Server online");
console.log(commands.NEXT);
});
function handleCommand(command) {
child = exec(command, function (error, stdout, stderr) {
// sys.print('Stdout ' + stdout);
// sys.print('Stderr ' + stderr);
if (error !== null) {
console.log('ERROR: ' + error);
}
})
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Cmus Remote</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="client.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body id="body">
<form action="/play">
<input id="play" type="submit" value="⏯">
</form>
</table>
</body>
</html>
Instead of using a form to "submit" the button, you can attach event handlers to the button that will do a POST request without reloading the page. Then, you won't need to send any redirects at all. Since you have JQuery on the page, I'll give an example with JQuery.
Index.html
<button id="play">Play</button>
<!-- Other code -->
<!-- Script or external JS code -->
<script>
$('#play').click(function(){
$.post('/play');
});
</script>