2

I am trying to link styles.css file to hello.html page to show up in the localhost using nodejs. But the output is only formatted in html and css styling isn't displayed.

Here is my code!

project.js

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

http.createServer(function (req,res){
    fs.readFile('hello.html',function(err,data){
    res.writeHead(200,{'Content-Type': 'text/html'});
    res.write(data);
    res.end();
  });

}).listen(8080); 

hello.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="heading">
    <h1>FILE UPLOADING!</h1>
</div>

<form method= "POST" enctype="multipart/form-data" action="fileupload">
<input type="file" name="filetoupload">
<input type="submit" id='bt' value="Submit">
</form>


</body>
</html>

style.css

#heading{
    color:green;
    font-family: sans-serif,serif;
}

#bt{
 background-color: #4CAF50;
color: #ffffff;
border-color: #4CAF50;
}
7
  • Are you requiring a CSS file in your HTML code? If that's the case, the browser will ask it to Node, and Node has to serve it and send it to the browser. Commented Jul 6, 2017 at 8:33
  • Yes.. check the html code. I've linked the css file. But doesn't work. Commented Jul 6, 2017 at 8:35
  • Does the styles.css exist in the same directory as the html file ? Commented Jul 6, 2017 at 8:37
  • Yes.. same directory..html works with css when viewed not in the localhost.. so basically I was wondering why it doesn't work on localhost using nodejs. Commented Jul 6, 2017 at 8:40
  • because you have no route for that. Node is low-level, it's not trying to be "smart" or anything. It's doing exactly what you're telling it to do. You're requesting a CSS file, but you wrote no instruction (no route, no folder indication) to handle this request. Now with Express, it's easy (that's even the whole point of Express), but in pure Node without Express, I don't know how to do it. Commented Jul 6, 2017 at 8:52

2 Answers 2

2

You can take refrence from the below link also you have to serve your css file also using http. Node.js serve multiple files in one request Code:

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

            http.createServer(function (req,res){
                if(req.url === '/hello.html') {
                fs.readFile('hello.html',function(err,data){
                res.writeHead(200,{'Content-Type': 'text/html'});
                res.write(data);
                res.end();
              });
                }
                else if(req.url === '/style.css') {
                fs.readFile('style.css',function(err,data){
                res.writeHead(200,{"Content-Type": "text/css"});
                res.write(data);
                res.end();
                });
                }

            }).listen(8080); 
Sign up to request clarification or add additional context in comments.

7 Comments

@sreekant-shenoy let know and approve the ans if it works for you :)
Also you can use express for better routing flexibility as mention by @Jeremy Thille in comments
Definitely, because this looks like a very verbose and tiresome way to handle routes.
Thanks everyone! its working.. I'll learn with express too. :)
@SreekantShenoy Can you accept my ans :D
|
1

you can try this!

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

http.createServer(function (req, res) {
    let route = req.url.replace('/', '')

    let request_url = route === '' || route === '/' ? 'hello.html' : route

    console.log(request_url)

    fs.exists(request_url, (exist) => {
        if (Boolean(exist) === false) {
            res.writeHead(404, {'content-type': 'text/html'})
            res.end('Page Not Found')
            return null
        }

        fs.readFile(request_url, function (err, data) {
            res.writeHead(200)
            res.write(data)
            res.end()
        })
    })
}).listen(8080)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.