Created
April 1, 2019 12:02
-
-
Save potikanond/33e00c63bc60ab30f98c929fda37dd0f to your computer and use it in GitHub Desktop.
Node.js - Simple HTTP Server#1 (lab tutorial)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const http = require('http'); | |
| const fs = require('fs'); | |
| const path = require('path'); | |
| const server = http.createServer( (req,res) => { | |
| console.log(req.url); | |
| if(req.url === '/') { | |
| // res.writeHead(200, { 'Content-Type': 'text/html'}); | |
| // res.end('<h1>This is index.html</h1>'); | |
| fs.readFile(path.join(__dirname, 'public', 'index.html'), (err,content) => { | |
| if(err) throw err; | |
| res.writeHead(200, { 'Content-Type': 'text/html'}); | |
| res.end(content); | |
| }); | |
| } else if (req.url === '/about') { | |
| // res.writeHead(200, { 'Content-Type': 'text/html'}); | |
| // res.end('<h1>This is ABOUT PAGE</h1>'); | |
| fs.readFile(path.join(__dirname, 'public', 'about.html'), (err,content) => { | |
| if(err) throw err; | |
| res.writeHead(200, { 'Content-Type': 'text/html'}); | |
| res.end(content); | |
| }); | |
| } else if (req.url === '/css/style.css') { | |
| fs.readFile(path.join(__dirname, 'public', 'css', 'style.css'), (err,content) => { | |
| if(err) throw err; | |
| res.writeHead(200, { 'Content-Type': 'text/css'}); | |
| res.end(content); | |
| }); | |
| } else if (req.url === '/api/users') { | |
| const users = [ | |
| { name: 'John Doe', age: 35 }, | |
| { name: 'Narathip Tiangtae', age: 25}, | |
| { name: 'Dome Potikanond', age: 30} | |
| ]; | |
| res.writeHead(200, { 'Content-Type': 'application/json'}); | |
| res.end(JSON.stringify(users)); | |
| } else { | |
| // res.writeHead(404, { 'content-type': 'text/html'}); | |
| // res.end('<h3>Eror 404: Not Found</h3>'); | |
| fs.readFile(path.join(__dirname, 'public', '404.html'), (err,content) => { | |
| if(err) throw err; | |
| res.writeHead(404, { 'Content-Type': 'text/html'}); | |
| res.end(content); | |
| }); | |
| } | |
| }); | |
| const PORT = process.env.PORT || 5500; | |
| server.listen(PORT, () => { | |
| console.log('Server is running on port: '+PORT); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment