Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

node server

// Create node.js server with routing. Create server.js file:
const http = require("http");

const server = http.createServer((req, res) => {
  // called every time request comes to the server (e.g. when you refresh page)
  console.log("request made: ", req.url); 
  
  // define what type of content you are sending (plain text or html or JSON file, etc.)
  res.setHeader("Content-Type", "text/html");

  // display response in browser
  res.write("<h1>Ladies and Gentlemans</h1>");
  res.write("<h2>We're in!</h2>");
  res.end();
});

server.listen(3000, "localhost", () => {
  console.log("listening for requests on port 3000"); // you can see this not in browser console, but in terminal
});

// Now, in terminal go to directory with server.js 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"

// NOTE: If you want to run external index.html file search in google/grepper for "node server index.html"
 
PREVIOUS NEXT
Tagged: #node #server
ADD COMMENT
Topic
Name
8+9 =