Vue页面部署在Node Koa服务器 Data 数据无法显示

摘要: 一个Vue页面部署在Node Koa服务器上,在html里无法显示vue data的数据, 接下来我会演示从发现问题 > 排查问题 > 解决问题的过程。如果只想知道如何解决问题,直接看解决问题板块
关键字: Node Vue 无法显示数据

问题描述

一个Vue页面部署在Node Koa服务器上,在html里无法显示vue data的数据, 但是用浏览器直接打开是可以的
重现代码
npm init -y; npm koa nunjucks

// 目录结构
app.js
index.html
<!-- index.html -->
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/element-ui/2.13.2/theme-chalk/index.css" rel="stylesheet">
</head>
<body>
    <div id="app">
        <h1>{{msg}}</h1>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.11/vue.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/element-ui/2.13.2/index.js"></script>
    <script>
        (function() {
            let vm = new Vue({
                el: "#app",
                data() {
                    return {
                        msg: 'Hello'
                    }
                }
            })
        }())
    </script>
</body>
</html>
// app.js
const Koa = require('koa')
const app = new Koa()
const nunjucks = require('nunjucks');

app.use(async (ctx, next) => {
    if (ctx.url == "/") {
        ctx.response.set('Content-Type', "text/html")
        ctx.response.body = nunjucks.render("index.html")
    }
    await next();
});
app.listen(3000);
console.log('app started at port 3000...');

node app.js

排查问题

  • 运行环境不同
    直接用浏览器打开可以显示data里的数据,在服务器上不行。所以我换了一个用Phpstudy搭建的PHP服务器, 部署在上面后访问页面,data里的数据可以显示。这时候可以断定是Node那边的问题了
  • 服务器返回文件的方式
    这时候,我没有想过要换一个服务器中间件,如express。因为我看到返回文件用的是nunjucks.render, 我在想会不会是因为这个原因。于是我换成了Node内置的fs模块, 问题就解决了
    if (ctx.url == "/") {
        ctx.response.set('Content-Type', "text/html")
        // ctx.response.body = nunjucks.render("index.html")
        ctx.response.body = fs.createReadStream("index.html")
    }
    

解决方案

  1. 页面使用<script>引入Vue.js 且用nunjucks返回文件的,可以考虑将nunjucks.render 换成 fs.createReadStream
  2. 排查问题策略
flowchat
st=>start: 遇到问题
op1=>operation: 找出与成功例子的不同之处
op2=>operation: 根据不同之处进行测试,缩小范围
op3=>operation: 导致这个问题的发生,可能有哪些因素。在范围寻找这些因素
e=>end: 结束



st->op1->op2->op3

参考资料

《调试九法——软硬件错误的排查之道》

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容