首页 > 解决方案 > Node 只向客户端发送 html 内容,而不是发送整个 Vue 应用程序

问题描述

我用 CLI 创建了一个新的 vue 项目并想要部署它。基于此文档

https://router.vuejs.org/guide/essentials/history-mode.html#html5-history-mode

我将历史模式添加到路由器。运行后,npm run build我采用了静态本机节点服务器的示例代码

https://router.vuejs.org/guide/essentials/history-mode.html#example-server-configurations

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

http.createServer((req, res) => {
  fs.readFile('../base/index.html', 'utf-8', (err, content) => {
    if (err) {
      throw err;
    }

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

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

所以当导航到localhost:3000vue 项目时似乎可以正确加载

在此处输入图像描述

但我有一个空白页,有两个错误

在此处输入图像描述

当我单击这些 js 文件时,它会显示 index.html 文件的内容。显然js是无法理解这个html内容的。我该如何解决这个问题?

标签: javascriptnode.jsvue.jsvue-clivue-cli-3

解决方案


服务器不会一次发送整个 vue 应用程序。

  • 当您浏览到该 url 时,浏览器会从服务器获取 html 文件。
  • 浏览器解析 html 文件。
  • 浏览器检测资产(js、图像、css)。
  • 浏览器请求这些文件。

它从服务器请求这些文件,但您尚未初始化服务器以查找这些文件。

所以,需要添加静态文件。

https://expressjs.com/en/starter/static-files.html

你可以参考这里


推荐阅读