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

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

作者: visitor009 | 来源:发表于2020-06-26 13:16 被阅读0次

摘要: 一个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

参考资料

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

相关文章

网友评论

      本文标题:Vue页面部署在Node Koa服务器 Data 数据无法显示

      本文链接:https://www.haomeiwen.com/subject/becefktx.html