简体   繁体   中英

Serve an HTML file including CSS

I have this code in a file called index1.html

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<title>Page Title</title>
</head>
<body>

<h1>My First Heading</h1>
<p>My first paragraph.</p>

<script src="./testing.js"></script>
<link rel="stylesheet" type="text/css" href="./formats.css" />

</body>
</html>

This is my testing.js file

$(document).ready(function(){
    $("p").click(function(){
        alert("The paragraph was clicked.");
    });
});

This is my formats.css file

body {
    color: blue;
}

p {
    color: green;
}

I'm hosting the html file on the local host with this file.

var http = require ('http');
var fs = require('fs');
var path = require('path');
var port = '2406';

function send404Response(response){
  response.writeHead(404, {"Content_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, {"Content-Type": "text/html"});
    fs.createReadStream(path.join(__dirname, "index1.html")).pipe(response);

  } else{
    send404Response(response);
  }
}

http.createServer(onRequest).listen(port);
console.log("Server is now running on port 2406...");

When I run running.js in node it doesn't include any of the formatting or the Jquery when I go to the local host. I'm wondering why this is the case and what I can do to fix it.

Your onRequest function only handles 1 possible url " / ".

You COULD add more if statements to serve the different files...

function onRequest(request,response){
  if(request.method == 'GET' && request.url == '/'){
    response.writeHead(200, {"Content-Type": "text/html"});
    fs.createReadStream(path.join(__dirname, "index1.html")).pipe(response);

  } else if (request.method == 'GET' && request.url == '/formats.css'){
    response.writeHead(200, {"Content-Type": "text/css"});
    fs.createReadStream(path.join(__dirname, "formats.css")).pipe(response);

  } else if (request.method == 'GET' && request.url == '/testing.js'){
    response.writeHead(200, {"Content-Type": "text/javascript"});
    fs.createReadStream(path.join(__dirname, "testing.js")).pipe(response);

  } else {
    send404Response(response);
  }
}

But you might want to look into an HTTP server framework like express.

Alternatively you may use npm 's http-server in your root directory via installing locally, and then able to host your index.html and its dependencies. You don't need to extra code or maintain scripts to host your pages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM