Vue history mode 的配置问题,启动 node 服务无法访问 js 和 css 等静态资源

今天试了试 history mode 的部署,打包好文件之后的结构如下
Screen Shot 2021-03-10 at 14.01.54.png
按照官方文档的后端配置例子,我先在nginx上进行了部署,访问没有任何问题。

然后我又试着用nodejs启动的web服务器进行访问,内容和官方给出的一样

const http = require('http')
const fs = require('fs')
const httpPort = 8090

http.createServer((req, res) => {
  fs.readFile('index.html', 'utf-8', (err, content) => {
    if (err) {
      console.log('We cannot open "index.html" file.')
    }

    res.writeHead(200, {
      'Content-Type': 'text/html; charset=utf-8'
    })

    res.end(content)
  })
}).listen(httpPort, () => {
  console.log('Server listening on: http://localhost:%s', httpPort)
})

我将该app.js文件放到打包后的dist文件夹的根目录中,然后node app.js启动,访问localhost:8090, 发现页面报错如下:
Screen Shot 2021-03-10 at 14.16.05.png
我看了请求,是页面上的script标签和link标签中的请求也返回了index.html文件,官方的这个node文件的写法似乎是有问题的,我对nodejs不是很熟,试着解析请求路径,如果是 js css 就返回对应的文件,但也还是没法访问。请大佬指教一下,这个node文件该怎么写。

阅读 2.1k
2 个回答

不能所有的請求都返回index.html,應該檢查請求的文件是否存在,存在返回文件,其他請求返回index.html

 if(path === '/'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.write(`哈哈`)
    response.end()
  } else if(path === '/x'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/css;charset=utf-8')
    response.write(`body{color: red;}`)
    response.end()
  } else {
    response.statusCode = 404
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.write(`你输入的路径不存在对应的内容`)
    response.end()
  }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题