在桌面创建一个用于存放server的目录,并且创建server.js
bash1 2 3 4 5
| cd ~/Desktop/ mkdir node-server cd node-server touch server.js vim server.js
|
编写服务器server.js
server.js1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| var http = require('http') var fs = require('fs') var url = require('url') var port = process.argv[2] if (!port) { console.log("请指定端口号,比如\nnode server.js 8888") process.exit(1) } var server = http.createServer(function(request, response) { var parsedUrl = url.parse(request.url, true) var path = request.url var query = '' if (path.indexOf('?') >= 0) { query = path.substring(path.indexOf('?')) } var pathNoQuery = parsedUrl.pathname var queryObject = parsedUrl.query var method = request.method console.log('得到 HTTP 路径\n' + path) console.log('查询字符串为\n' + query) console.log('不含查询字符串的路径为\n' + pathNoQuery) response.write('hi') response.end() }) server.listen(port) console.log('监听 ' + port + ' 成功\n请打开 http://localhost:' + port)
|
运行server.js服务器
这里一个括号空格都不能错,如果报错则百度一下错误代码。这样server.js就成功运行起来了,server.js开始监听8888端口,开始接受来自client的服务请求。
测试
保持这个gitbash窗口运行,新建一个gitbash窗口 curl
一下 http://localhost:8888/docName
来测试一下server.js是否能响应请求
服务器正确监听到curl对于8888端口的请求并打印出请求的路径,并给出response:hi,而后end了这个response,此时client收到应答结束了会话回到了可以输入命令行的界面,而server继续处于等待请求的状态,我们使用ctrl+c来中断server.js的进程。
使用 curl -s -v — “http://localhost:8888/docName”
可以查看完整的请求和响应
完整代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| var http = require('http') var fs = require('fs') var url = require('url') var port = process.argv[2] if (!port) { console.log("请指定端口号,比如\nnode server.js 8888") process.exit(1) } var server = http.createServer(function(request, response) { var parsedUrl = url.parse(request.url, true) var path = request.url var query = '' if (path.indexOf('?') >= 0) { query = path.substring(path.indexOf('?')) } var pathNoQuery = parsedUrl.pathname var queryObject = parsedUrl.query var method = request.method console.log('HTTP 路径为\n' + path) if (path == '/style.js') { response.setHeader('Content-Type', 'text/css; charset=utf-8') response.write('body{background-color: #ddd;}h1{color: red;}') response.end() } else if (path == '/script.html') { response.setHeader('Content-Type', 'text/javascript; charset=utf-8') response.write('alert("这是JS执行的")') response.end() } else if (path == '/index.css') { response.setHeader('Content-Type', 'text/html; charset=utf-8') response.write('<!DOCTYPE>\n<html>' + '<head><link rel="stylesheet" href="/style.js">' + '</head><body>' + '<h1>你好</h1>' + '<script src="/script.html"></script>' + '</body></html>') response.end() } else { response.statusCode = 404 response.end() } }) server.listen(port) console.log('监听 ' + port + ' 成功\n请打开 http://localhost:' + port)
|