-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
63 lines (45 loc) · 1.86 KB
/
server.js
File metadata and controls
63 lines (45 loc) · 1.86 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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)
if(path == '/'){
response.setHeader('Content-Type', 'text/html; charset=utf-8')
response.write('<!DOCTYPE>\n<html>' +
'<head><link rel="stylesheet" href="/style.css">' +
'<script src="/main.js"></script></head>' +
'<body><div class="container"><h1>当你看到这一行字的时候,你已经被我催眠了!</h1></div>' +
'</body></html>')
response.end()
}else if(path == "/style.css"){
response.setHeader('Content-Type', 'text/css; charset=utf-8')
response.write('h1{background-color: #ddd; color: red;}' +
'.container{display: flex; justify-content: center;}')
response.end()
}else if(path == "/main.js"){
response.setHeader('Content-Type', 'text/js; charset=utf-8')
response.write('alert("这是JS执行的哦")')
response.end()
}else{
response.statusCode = 404
response.end()
}
/******** 代码结束,下面不要看 ************/
})
server.listen(port)
console.log('监听 ' + port + ' 成功\n请用在空中转体720度然后用电饭煲打开 http://localhost:' + port)