Vue.js + Node.js: 服务器配置在哪里

Vue.js + Node.js: Where is Server Config

(注意:这里完全擦写了代码,所以如果我说的很傻,请理解。)

我使用典型的 webpack 模板开始了一个 Vue.js 项目,用于制作单页应用程序。 (我没有从这里修改文档结构。)上面没有其他框架。

为了摆脱 URL 中的散列,文档谈到了打开 history mode。但是,在指定之后,您必须配置服务器。引用;

[...] add a simple catch-all fallback route to your server. If the URL doesn't match any static assets, it should serve the same index.html page that your app lives in.

由于我使用的是 Node.js + Vue.js,上面没有添加任何其他内容,因此这应该是服务器配置的相应示例。

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

http.createServer((req, res) => {
  fs.readFile('index.htm', 'utf-8', (err, content) => {
    if (err) {
      console.log('We cannot open "index.htm" 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)
})

但是,我终其一生都无法弄清楚它应该去哪里,因为它没有具体说明。这会进入 main.js 吗?路由器的index.js?或者它是构建文件夹或配置中的其中一个东西的一部分? (如果我在 heroku 上 运行 生产版本会有什么不同吗?)

webpack 模板附带 webpack-dev-server(基于 Node.js)已经为历史模式准备好了:在 开发 你的应用通过 npm run dev.

当您通过 npm run build 部署 您的应用程序时,您必须应用文档中显示的服务器配置,这将创建一个 /dist 文件夹,其中您可以自由上传到任何静态服务器的内容(不一定 Node.js)。

示例代码是 Node.js 服务器的主脚本,但它非常简单,returns index.html 的内容(还有一个 [=代码中的 30=],对于任何请求都应该是 .html 而不是 .html),但这会破坏任何其他资产请求,例如 CSS 或 JS。它仅用于演示目的:使用 index.html.

响应任何路由 (URL)

如果您计划部署到 Node.js 服务器,您应该寻找更好的脚本。