Dieses Blog durchsuchen

Freitag, 19. August 2016

node.js: create the simplest webserver

Let's create a simple webserver with node.js

Prerequisits

node.js installed
npm installed

Create project

Type follwing command in your terminal and follow the instruction
$ npm init


This will create a package.json, which contains all the needed information for your project

Create a webserver


A webserver is just a piece of code in that case, wich allows us to send a message to the users browser.

Create a file "server.js" and paste follwing code
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
view raw server.js hosted with ❤ by GitHub

This will require the package http, which contains the server functions.
Then it will bind the server on localhost on port 3000. After that It will send a static returnvalue "Hello world" to the browser, wenn a user calls http://localhost:3000

Start the webserver

Open a terminal in the projectroot and type:
$ node server.js 


Now you can surf http://localhost:3000 and you should see "Hello World"

Thats it

Keine Kommentare:

Kommentar veröffentlichen