如何使用NodeJs创建HTTP服务?
- http-server.js
1const http = require('http')2http.createServer(function (req, res) {3 res.writeHead(200, {4 'Content-Type': 'text/plain'5 })6 res.end('Hello World')7}).listen(80, '127.0.0.1')89console.log('Server running at http://127.0.0.1:80/')
- 浏览器访问
- 用curl访问
curl -v http://127.0.0.1:80
看一下请求报文
1// 三次握手2* Rebuilt URL to: http://127.0.0.1:80/3* Trying 127.0.0.1...4* TCP_NODELAY set5* Connected to 127.0.0.1 (127.0.0.1) port 80 (#0)67// 客户端向服务端发送请求报文8> GET / HTTP/1.19> Host: 127.0.0.1:8010> User-Agent: curl/7.54.011> Accept: */*12>1314// 服务端响应客户端内容15< HTTP/1.1 200 OK16< Content-Type: text/plain17< Date: Wed, 04 Aug 2021 15:55:55 GMT18< Connection: keep-alive19< Keep-Alive: timeout=520< Transfer-Encoding: chunked21<22* Connection #0 to host 127.0.0.1 left intact23Hello World%
- htttp-client.js
1const http = require('http')23const options = {4 hostname: '127.0.0.1',5 port: 80,6 path: '/',7 method: 'GET'8}9const req = http.request(options, (res) => {10 console.log(`Status=${res.statusCode}, Headers=${JSON.stringify(res.headers)}`);11 res.setEncoding('utf8')12 res.on('data', (data) => {13 console.log(data)14 })15})16req.end()