Node.Js Sending CSS Files

How can I include css files using node, express, and ejs?

Use this in your server.js file

app.use(express.static(__dirname + '/public'));

and add css like

<link rel="stylesheet" type="text/css" href="css/style.css" />

dont need / before css like

<link rel="stylesheet" type="text/css" href="/css/style.css" />

node.js sending css files

You're only writing a response header for css requests, for one.

I'd imagine if you call curl -I http://your-server/some-file.css, you'd get back a 200 status with a Content-Length of 0. You could just get away with:

res.write(fs.readFileSync(__dirname + path, 'utf8'));

But a.) Don't Repeat Yourself, and b.) the 'sync' in both of those methods means synchronous. It probably isn't for this version, but in Node in general, you should be just calling readFile and passing a callback to finish the request later on. The API isn't great for directly linking, but the File System section should help, look for 'fs.readFile'.

express: how to send html together with css using sendFile?

The browser should load style.css on its own, so you can serve that as a route:

app.get('/style.css', function(req, res) {
res.sendFile(__dirname + "/" + "style.css");
});

However, this would get very cumbersome very quickly as you add more files. Express provides a built in way to serve static files:

https://expressjs.com/en/starter/static-files.html

const express = require("express");
const app = express();
app.use(express.static(__dirname));

Keep in mind that if index.html is in the same directory as your server code you will also serve the server code as static files which is undesirable.

Instead you should move index.html, your css, images, scripts, etc. to a subdirectory such as one named public and use:

app.use(express.static("public"));

If you do this, Express will serve index.html automatically and you can remove your app.get("/" as well.

Serving css files with nodejs

I have modified your code (which is working). Have a look at it:

var http = require('http');
var fs = require('fs');

http.createServer((req, res) => {
console.log(req.url)
if (req.url === "/") {
fs.readFile('index.html', (err, html) => {
if (err) {
throw err;
}
res.setHeader('Content-type', 'text/html');
res.write(html);
res.statusCode = 200;
res.end();
});
}
else if (req.url == '/style.css') {
res.setHeader('Content-type', 'text/css');
res.write(fs.readFileSync('style.css'));
res.end();
} else {
res.write("invalid request")
res.end();
}
}).listen(3000);

console.log('server running @ 3000');

Here is the HTML file:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="/style.css" />
</head>
<body>
Hello
</body>
</html>

and style.css

body {
color: red;
}

You need to return your files based on your request. For example, in this scenario, the HTML file is requesting the server for /style.css, the server looks at the code and finds the block which deals with that request

 else if (req.url == '/style.css') {
res.setHeader('Content-type', 'text/css');
res.write(fs.readFileSync('style.css'));
res.end();
}

And finally returns the file. I hope that helps.

Recommendation:

Use express.js (https://expressjs.com/).
It is really fast minimal and easy to use NodeJS routing framework which follows the MVC pattern. There are lots of resources on youtube and google for this framework.

Express.js not sending css file

You get this error usually when there is no CSS file under that link.

When you use app.use(express.static('public')); directly express serves everything under root endpoint.

So you can use <link type="text/css" rel="stylesheet" href="/styles/index.css">.

If you would like to use /public/xxx.css you can use

app.use('public', express.static('public'));

Sending both html and css file on the res.sendfile express js

You can use express.static to server static files like:

Suppose your folder structure:

app.js
| +-- public
| | +-- css
| | | +-- mystyle.css
const express = require("express");
const app = express();

// using express you don't need this
// const http = require("http").Server(app).listen(3000);

// server your css as static
app.use(express.static(__dirname + 'public'))

console.log("Server Started");

app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html");
})

// start your server
app.listen(3000, () => console.log('Server started at port 3000'))

In your html

<link href="css/mystyle.css"

How do I use CSS and JS files within a HTML file being sent with Express?

You need to define a static files directory. Create a folder called public and then include this line:

app.use(express.static('public'));

Don't include public in the file path when you include the css file though. All of your static files can go in that folder. Or, better still, create sub-folders for styles, images, fonts etc.

You can read more about it here: https://expressjs.com/en/starter/static-files.html

I think the problem you're having is that you're trying to create a web application from scratch using Express without any of the surrounding functionality. Your app sends a file when you navigate to the URL. It does not listen for specific requests for files and respond to them, it does not handle missing files, server errors etc.

You could do all that from scratch but in fact Express have created an application generator which creates a skeleton app for you with the web server, public folder, routes etc. It's called Express Generator and you can find it here: https://expressjs.com/en/starter/generator.html

That's a brilliant starting point for an MVC application. You get the package.json file for additional node modules, a template engine called Jade (although I prefer Hogan) for dynamic content and once it's created your app, you can fire it up by typing "npm start" in a console window.



Related Topics



Leave a reply



Submit