【问题标题】:export json object from .json file to vue through express and assign it to the variable通过 express 将 json 对象从 .json 文件导出到 vue 并将其分配给变量
【发布时间】:2016-08-25 15:32:57
【问题描述】:

我想在我的页面上显示一些我在 dsa.json 文件中的数据。我在 vue 中使用 express。

这是我在 server.js 中的代码:

var data;
fs.readFile('./dsa.json', 'utf8', (err, data) => { 
  if (err) throw err;
  exports.data = data;
});

这是 index.html 中 <script> 标记之间的代码

var server = require(['../server']);
var data = server.data;
var scoreboards = new Vue({
    el: '#scoreboard',
    data: {
        students: data
    }
});

我正在使用 requirejs (CDN) 在 index.html 中的 <script> 标记之间要求服务器。

index.html 在公共目录中,而 dsa.json 和 server.js 在主目录中。

这是我在客户端中遇到的错误:

require.min.js:1 GET http://localhost:3000/server.js 
require.min.js:1 Uncaught Error: Script error for "../server"

我认为这与上下文和范围有关,但我不知道具体是什么。

我正在使用 Chrome。

【问题讨论】:

    标签: json express vue.js


    【解决方案1】:

    你的方法是完全错误的。您不能在页面上包含服务器脚本。另外,我不是 NodeJS 忍者,但我认为导出函数内部的数据不会起作用 -> exports.data = data

    解决方法:

    服务器端:

    const fs = require('fs');
    const express = require('express');
    const app = express();
    
    const data = fs.readFileSync('./dsa.json', 'utf8'); // sync is ok in this case, because it runs once when the server starts, however you should try to use async version in other cases when possible
    
    app.get('/json', function(req, res){
      res.send(data);
    });
    

    客户端:

    var xhr = new XMLHttpRequest();
    xhr.open('GET', '/json', true);
    xhr.addEventListener('load', function() {
      var scoreboards = new Vue({
        el: '#scoreboard',
        data: {
            students: JSON.parse(xhr.response)
        }
      });
    });
    xhr.addEventListener('error', function() {
      // handle error
    });
    xhr.send();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-16
      • 2015-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多