export json object from .json file to vue through express and assign it to the variable
export json object from .json file to vue through express and assign it to the variable
我想在我的页面上显示 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 在 public 目录中,而 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。
你的做法是完全错误的。您不能在页面上包含服务器脚本。另外,我不是 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();
我想在我的页面上显示 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 在 public 目录中,而 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。
你的做法是完全错误的。您不能在页面上包含服务器脚本。另外,我不是 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();