【问题标题】:Node only sends html content to the client instead of sending a whole Vue appNode 只向客户端发送 html 内容,而不是发送整个 Vue 应用程序
【发布时间】:2020-01-31 12:07:13
【问题描述】:

我使用 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内容的。我该如何解决这个问题?

【问题讨论】:

    标签: javascript node.js vue.js vue-cli vue-cli-3


    【解决方案1】:

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

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

    它从服务器请求这些文件,但您还没有初始化服务器来查找这些文件。

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

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

    可以参考here

    【讨论】:

      【解决方案2】:

      作为@Sukul 之前的回答,您只需要处理静态文件,因为您现在只有一个处理程序来处理 HTML 文件(挂载点文档)附带的所有请求,并且当它请求 *.js 应用程序时期待有效的 javascript 语法,而不是找到 HTML,以及网络选项卡上的错误消息是什么

      const http = require('http')
      const fs = require('fs')
      const nStatic = require('node-static');
      var fileServer = new nStatic.Server('./public');
      
      const httpPort = 3000
      
      const controllers = (req,res)=>{
        if(req.url.includes(".")
         return fileServer.serve(req, res);
        else
        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)
        })
      }
      }
      
      http.createServer(controllers).listen(httpPort, () => {
        console.log('Server listening on: http://localhost:%s', httpPort)
      })
      

      node-static ref

      但是,我强烈建议您尝试使用 express.js

      【讨论】:

        猜你喜欢
        • 2019-12-16
        • 2020-12-17
        • 2017-08-11
        • 1970-01-01
        • 2021-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-13
        相关资源
        最近更新 更多