javascript - 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:3000
vue 项目时似乎可以正确加载
但我有一个空白页,有两个错误
当我单击这些 js 文件时,它会显示 index.html 文件的内容。显然js是无法理解这个html内容的。我该如何解决这个问题?
解决方案
服务器不会一次发送整个 vue 应用程序。
- 当您浏览到该 url 时,浏览器会从服务器获取 html 文件。
- 浏览器解析 html 文件。
- 浏览器检测资产(js、图像、css)。
- 浏览器请求这些文件。
它从服务器请求这些文件,但您尚未初始化服务器以查找这些文件。
所以,需要添加静态文件。
https://expressjs.com/en/starter/static-files.html
你可以参考这里
推荐阅读
- linux - 如何验证给定的参数格式,根据参数格式将执行不同的脚本
- python - 使用交叉验证时如何使用测试数据集进行预测?
- javascript - puppeteer page.evaluate 页面未定义
- c# - Blazor WebAssembly;.net core SignalR Client;调用 HubConnectionBuilder.Builder() 时抛出 InvalidOperationException
- r - 使用集成卡尔曼滤波器计算具有新初始值的新预测值
- excel - 比较两个表之间的数据并更新另一行中的值
- c# - 您能否建议从 NetworkStream 频繁使用异步与同步读取/写入小数据包?
- xml - XSLT如何删除不匹配节点的值
- javascript - 有没有办法修复 window.open 中的嵌套 document.write?
- ajax - 带有 HTTP/2 和 ajax 调用的 WCF 请求-响应对