# Node.js - Building a serever Node comes with its own `http` built-in module ## using `http` module ```javascript const http = require('http'); // grab the 'http' module const server = http.createServer( ()=> { //console.log('headers', request.headers) console.log('method', request.method) console.log('url', request.url) const user = { name: 'John', hobby: 'Skating' } response.statusCode = 200; response.setHeader('Content-Type', 'application/json'); response.end(JSON.stringify(user)); }) server.listen(3000); ``` - `const http = require('http');`: grab the buit-in `http` module - `http.createServer( (req, res) ⇒ {…} )`: The `createServer()` method of `http` creates a new HTTP server and returns it. - `server.listen(3000)`: open a port `3000` ### Run the file ```shell $ node server.js ``` 1. Go to [localhost:3000](http://localhost:3000/) (nothing seems to happen) 2. Back to terminal: `server.js` is running in Node ![](https://i.imgur.com/hfGJypu.png) ## Add params: `request` & `response` ```javascript const http = require('http'); // create server const server = http.createServer( (request, response)=> { console.log('headers', request.headers); console.log('methods', request.method); console.log('url', request.url); response.setHeader('Content-Type', 'text/HTML'); response.end('<h1>Helllloooooo</h1>'); }); server.listen(3000); ``` ### request 對方要求進入 web server,關於使用者的詳細資訊物件 (e.g. `request.url`) ### response * response.statusCode * response.setHeader('Content-Type', 'application/json') * response.end() ## 相關 API 語法 ```javascript const http = require("http"); // create server http.createServer(function(req,res){ res.writeHead(200,{"Content-Type":"text/plain"}) res.write("Hello") res.end() }).listen(8080); ``` Another way: take out the function ```javascript const requestListener = async(req, res)=>{ console.log(req.url); res.end(); } const server = http.createServer(requestListener); server.listen(8080); ``` - header info - `.writeHead( 200, {"Content-Type":"text/plain"} )` - `200`: statusCode - `{"Content-Type":"text/plain"}` - `.setHeader('Content-Type', 'text/HTML')` - `.write` - `.end()` - 結束這次的請求 - `.listen(8080)` - 開啟一個 port ## port `127.0.0.1:3000` - `127.0.0.1` - 由自己的電腦所開啟的 web server 伺服器 (`localhost`) - `:3000` - 伺服器其中一個軟體,佔據電腦裡其中一個 port `3000` - `:21` - ftp - `:3389` - 遠端桌面 ## Run the file Use nodeman we've set before: ```shell $npm start ``` Visit [localhost:3000](http://localhost:3000/): ![](https://i.imgur.com/Kgfslrq.png) - `Status Code`: 200 - `Content-Type`: text/HTML Back to terminal & check the request: ![](https://i.imgur.com/2ToMvya.png) ## Example: Grab a JSON file ```javascript const http = require('http'); // grab the http module const server = http.createServer( (request, response)=> { //create an object const user = { name: 'John', hobby: 'skating' } // set content-type to JSON response.setHeader('Content-Type', 'application/JSON'); // turn the object into JSON response.end(JSON.stringify(user)); }) server.listen(3000); ```