Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

node server index.html

// Create server.js file:
const http = require("http");
const fs = require("fs"); // this is filesystem which allows to read and save external files

const server = http.createServer((req, res) => {
  
  // set header content type
  res.setHeader("Content-Type", "text/html");

  // send html file
  fs.readFile("./views/index.html", (err, data) => {
    if (err) {
      console.log(err);
    } else {
      res.end(data);
    }
  });
});

server.listen(3000, "localhost", () => {
  console.log("listening for requests on port 3000");
});

// In directory with server.js create folder "views" and inside create file "index.html":
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Full success</title>
</head>
<body>
    <h1>Ladies and Gentlemans</h1>
    <h2>We're in!</h2>
</body>
</html>

// Now, open directory with server.js in terminal and run:
node server.js

// You can see the results in browser at http://localhost:3000

// NOTE: If you want to handle different adresses/pages/routes like /about, /contact or /blog search in google/grepper for "node server with routes"
 
PREVIOUS NEXT
Tagged: #node #server
ADD COMMENT
Topic
Name
1+4 =