3

I would like to display on my page some data which I have in dsa.json file. I am using express with vue.

Here's my code from the server.js:

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

Here's code from between <script> tags in index.html

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

I am using requirejs (CDN) to require server between <script> tags in index.html.

index.html is in public directory whereas dsa.json and server.js are in the main catalogue.

Here are the errors I get in the client:

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

I think it has something to do with context and scope but I don't know what exactly.

I am using Chrome.

1 Answer 1

1

Your approach is completely wrong. You can't include the server script on your page. Also, I'm not a NodeJS ninja, yet I don't think that exporting the data inside the function will work -> exports.data = data.

The workaround:

Server side:

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);
});

Client side:

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.