user6512265
user6512265

Reputation:

Can't get css file in node

I just started learning Node.js and I have a small problem with getting data from css file. When I add data to the index file code it works.

Here are my codes:

app.js

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

//404 response

function send404response(response) {
  response.writeHead(404, {
    "Context-Type": "text/plain"
  });
  response.write("Error 404: Page not found!");
  response.end();
}

function onRequest(request, response) {
  if (request.method == 'GET' && request.url == '/') {
    response.writeHead(200, {
      "Context-Type": "text/html"
    });
    fs.createReadStream("./index.html").pipe(response);
  } else {
    send404response(response);
  }
}

http.createServer(onRequest).listen(8888);
console

index.html

<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="main.css" >
    <title>First node app</title>
</head>
<body>
<div class="header"></div>
<div class="container">Welcome to my first website! <br> This website is  created in NodeJs!</div>
</body>
</html>

main.css

* {
  margin: 0px;
  padding: 0px;
}

body {
  background: url('https://i.sstatic.net/1voHP.png') repeat;
  font-size: 100%;
}

.header {
  width: 100%;
  height: 500px;
  background: rgba(0, 0, 0, .9);
}

.container {
  font-size: 1em;
  margin: 0 auto;
  width: 70%;
  height: 90%;
  background: rgba(0, 0, 0, .3);
  padding: 5%;
}

* {
  margin: 0px;
  padding: 0px;
}

body {
  background: url('https://i.sstatic.net/1voHP.png') repeat;
  font-size: 100%;
}

.header {
  width: 100%;
  height: 500px;
  background: rgba(0, 0, 0, .9);
}

.container {
  font-size: 1em;
  margin: 0 auto;
  width: 70%;
  height: 90%;
  background: rgba(0, 0, 0, .3);
  padding: 5%;
}

They are all in same folder.

Upvotes: 0

Views: 230

Answers (1)

Quentin
Quentin

Reputation: 944568

if( request.method == 'GET' && request.url == '/' ){
    response.writeHead(200, {"Context-Type": "text/html"});
    fs.createReadStream("./index.html").pipe(response);

So if the browser asks for / then you'll send them the homepage…

}else{
    send404response(response);

… and if the browser asks for anything else you'll send a 404 error.

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

So when the browser asks for /main.css … you'll send a 404 error.

You need to write some code to actually handle the case of the browser asking for /main.css.

Upvotes: 1

Related Questions