Node Web Server
Creating a Web Server
Developer can create a web server with Node built-in http
module, which allows Node to transfer data over the Hyper Text Transfer Protocol (HTTP). To include the HTTP module, use the require()
method and specify hostname and port. Use the createServer()
method to create an HTTP server.
The function passed into the http.createServer()
method, will be executed when someone tries to access specified hostname and port. A Request object req
encapsulates the HTTP request sent by the user, which is the first argument. The HTTP response that is returned to the user is generated by interacting with the Response object res
which is the second argument.
server.js | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Web server can be started with node:
1 2 |
|
Try it from your browser and you should see 'Hello World!' text in your browser.
Status code 200 tells the clients browser that the request succeeded. Check out other HTTP response status codes from Mozilla Developer Network HTTP response status codes.
Returning a HTML content
Server can be easily modified to returning a HTML just changing the content type to text/html
.
1 2 3 |
|
Try it from your browser and you should see 'Hello World!' header in your browser.
A HTML file can be read from the filesystem with Node's fs
module and then send it to the client in the response.
server2.js | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
We will work more web servers with Express.
Read more
Goals of this topic
Understand
- Node Web Server