- Modern JavaScript Web Development Cookbook
- Federico Kereki
- 171字
- 2021-07-02 14:50:01
How to do it…
Getting ahead a bit, let's set up a very basic server, which will answer all the requests by sending back a 'Server alive!' string. For this, we will need to follow three steps:
- Use require() to import the http module of Node—we'll see more on modules in the next section; for the time being, just assume that require() is equivalent to import.
- Then, use the createServer() method to set up our server.
- After that, provide a function that will answer all requests by sending back a text/plain fixed answer.
The following code represents the most basic possible server, and will let us know whether everything has worked correctly. I have named the file miniserver.js. The line in bold does all the work, which we'll go over in the next section:
// Source file: src/miniserver.js
/* @flow */
"use strict";
const http = require("http");
http
.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Server alive!");
})
.listen(8080, "localhost");
console.log("Mini server ready at http://localhost:8080/");