Load client Javascript and CSS in Node.js -
i want load client side javascript chat.jsand css style.css in html file 404 error while loading them.
this server file:
// routing app.get('/', function (req, res) { res.sendfile(__dirname + '/index.html'); }); this client html:
<script src="/socket.io/socket.io.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src="chat.js"></script> <link rel="stylesheet" type="text/css" href="style.css"> how can load them in app? files in same root folder. tried doesn't work:
app.get('/', function (req, res) { res.sendfile(__dirname + '/chat.js'); });
looks using express web framework in case should use express static middleware purposes.
i did example below.
here server server.js file:
var express = require('express'); var app = express(); app.use(express.static(__dirname + '/public')); app.listen(4040, function() { console.log('server , running'); }); where see express serving files resides on public directory. see didn't provide route / since browser automatically going grab index.html.
public/index.html:
<!doctype html> <html> <head> <link href="style.css" rel="stylesheet"/> </head> <body> <h1>hey</h1> <script src="app.js"></script> </body> </html> from perspective of browser knows index.html, app.js, , style.css files since provided express.
public/style.css:
body { background: red; } public/app.js
document.addeventlistener('domcontentloaded', function() { alert('hello world'); });
Comments
Post a Comment