北京经济技术开发区经开区虚拟城市项目-【前端】-移动端Web
lixuliang
2024-05-08 f5233339920a59103d53e8efadc6f3f5d0b64f31
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
62
63
64
65
const http = require('http')
const url = require('url')
const fs = require('fs')
const path = require('path')
// const mime = require('mime')
 
const mime = {
  map: {
    'html': 'text/html',
    'xhtml': 'application/xhtml+xml',
    'xml': 'text/xml',
    'js': 'application/javascript',
    'wasm': 'application/wasm',
    'map': 'magnus-internal/imagemap',
    'css': 'text/css',
    'png': 'image/png',
    'jpg': 'image/jpeg',
    'jpeg': 'image/jpeg',
    'gif': 'image/gif',
    'ico': 'image/vnd.microsoft.icon'
  },
  getType: function (ext) {
    let conType = this.map[ext]
    return conType || 'text/plain'
  }
}
 
const httpServer = http.createServer()
 
httpServer.on('request', (req, res) => {
  console.log(`[receive request] ${req.method} ${req.url}`)
 
  const urlJson = url.parse(req.url)
  let { pathname } = urlJson
  if (pathname === '/') pathname += 'index.html'
  let ext = pathname.split('.').pop()
 
  // all
  res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin')
  res.setHeader('Cross-Origin-Embedder-Policy', 'require-corp')
  res.setHeader('Cross-Origin-Opener-Policy', 'same-origin')
  // just page file
  // if (ext === 'html' || ext === 'htm' || ext === 'xhtml' || ext === 'js') {
  //   res.setHeader('Cross-Origin-Embedder-Policy', 'require-corp')
  //   res.setHeader('Cross-Origin-Opener-Policy', 'same-origin')
  // }
 
  let contentType = mime.getType(ext)
  res.setHeader('Content-Type', contentType)
 
  fs.readFile(path.resolve(__dirname, pathname.substr(1)), (err, data) => {
    if (err) {
      res.writeHead(404)
      res.end('Not found.')
    } else {
      res.writeHead(200)
      res.end(data)
    }
  })
})
 
const PORT = 9000
httpServer.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}`)
})