How to pass/import server-side JSON to a vue app? - javascript

I'm building a webapp that requires a JSON file as data. The person using my app in their website should be able to pass in a JSON file hosted on their server so that my app can read it.
In development, I just used import mydata from "./mydata.json", but this won't work in production. I tried to have a computed property that returns require (this.publicPath + this.datapath) (where this.publicPath is process.env.BASE_URL, but it's not able to find the file (if it's relevant, I'm using vue-cli to build).
The structure of my app is that I have a wrapper App.vue and then the main component, main-component.vue (so that I can pass a prop containing data to the main component).
What's the best way to do this? I've tried using a <script> tag in index.html, but apparently that's not supported with JSON. I don't want to use other libraries like jQuery.
(I'm thinking that I could have the user just import their file with the ES6 syntax by creating a new Vue component/app, but I'm not sure how to do that in pure HTML).

As an extension of my comment: what you're looking for is to actually fetch the JSON from your server using an XMLHttpRequest. You can do this in a modern, ES6-manner using the Fetch API:
fetch('/path/to/your/json')
.then(resp => resp.json())
.then(data => {
// Access the parsed JSON as `data`
console.log(data);
});

If you can try using a .js file that migh work and you can structure the data the same way as in a .json file, afterall a json is just a js object, also i had this problem while doing the same thing.
DISCLAIMER: you might have to restructure your data to be in an exported variable if that is possible, like so:
export const myObj = {your json}

Related

Read in JSON at runtime in React Webpack app

I have a small React/Webpack app where I import a JSON file at the top of the file. At buildtime, the contents of the JSON are read into the resulting bundle.js. If I then make changes the the JSON file I need to re-build the app for the React app to change.
Is there a way to get it so the React app will read in the JSON file at runtime?
One idea I had was to manually edit the output HTML to read mydata.js (in addition to bundle.js) and then mydata.js would just assign window.mydata to the data. Then the React app would read in from the window global object. But I think that's a hacky solution curious to see if there are better paths. Thanks!
You can move the json file in the public folder of your react app (so it's served as a static asset) and then use a fetch call to access it. Attention: this will be much slower at execution time (as the browser needs to execute an additional HTTP request).

Exporting a webpage containing VueJS to a locally stored HTML file

Usecase: I want to allow users to download a static export of a webpage containing VueJS as a Javascript framework.
I've tried to export using filesaver.js and blob with mimetype text/html, replacing relative paths to the original host so that these payloads are delivered by the webserver:
let host = window.location.origin
let html_string = document.documentElement.outerHTML
html_string = html_string.replace(/\/build\//g, host+'/build/')
var fileblob = new Blob([html_string], { type: 'text/html' })
this.filesaver.saveAs(fileblob, this.title+".html");
However, the result is a page with correct styling and application javascript, but without any interaction.
VueJS is not detected by the debugger, but the window does have a window.vm containing the Vue instance.
The same behavior occurs when I try to save the file through the browser as self contained html file (.mhtml extension). Webpage looks proper with all styling and scripts included, but there's no actual javscript being executed.
What am I missing here?
Ok, posting for posterity:
The problem was that the components in the file were already replaced by their VueJS templates in the original html, and therefore not being mounted in the downloaded static file.
The solution was to generate the HTML in the backend (in this case with a Laravel render()) function, and stream that into a file for the user. This file then does contain the correct components, which are in turn substituted by the VueJS javscript.

How to read a local server JSON file with react?

I need to read a JSON file located on my machine with my react application and nothing seem to work.
I tried importing fs (with import and require) but it returns a blank object and I cannot use any of it's functions.
Jquery doesn't seem to find my file either.
Everywhere I searched they use FS, Jquery or FileReader (the last one is always used for files that the client uploaded to the page).
This is one of the solutions I tried with FS:
const fs = require("fs");
export default function getJson() {
let rawdata = fs.readFile("file.json");
let json = JSON.parse(rawdata);
console.log(json);
}
When I reload the browser
TypeError: fs.readFile is not a function
With Jquery I tried this:
import $ from "jquery";
export default function getJson() {
$.getJSON("file.json", function() {
console.log("success");
});
}
The console shows this:
Failed to load resource: the server responded with a status of 404 (Not Found)
I hope you can help me.
Thanks in advance!
fs is an inrospection that connects Node's engine to the underlying OS. It does not exist in browser code (e.g. ReactJS).
For security measures, browsers deny JS from interacting with the underlying platform. So to read the file, you have two option (as far as I know):
Either create a file-input field in html (like the file-upload fields you usually see). Or you need to serve the file by some server. You can put the file in your assets folder, and then request it in react.
Update 1:
From my experience, one of the easier ways to include a "runtime-configuration" is to serve the configuration as an asset.
I don't have much experience in ReactJS, but the idea is the same.
Let's say you put the config.json in Public/json/config.json. Then you can read this file from the application by requesting it.
here's an example:
fetch("/json/config.json").then(resp=>resp.json()).then(console.log);
and here's a small working stackblitz example

How to read a value from properties file in a javascript file

I have a spring-boot project which serves angularjs. Both the front-end and back-end code are in the same project.
In my angularjs service.js files I am calling the back-end service.
I have different urls in the different properties file. I want to read them as per profile selection. I know how to read properties file in a Java class but I am not sure how to read values from properties file in a javascript file.
As shown below:
Some options:
create a separate config.json for your angular APP (manage it manually).
use maven resource plugin to filter placeholders for your config.json file (automated). E.g. read in one place and substitute in another (but I don't like this way).
Or create an API to return data from from your properties file as JSON.
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

How to read json file located in both folder in meteor?

I need to read a language json file from both folder but in client side seems not accessible.
you should familiarize yourself with the Meteor application structure, which you can find here:
https://guide.meteor.com/structure.html
there are a couple different ways to do what you want. following the guide, i have such code in the /imports area, in a directory that is served to both client and server. e.g.
/imports/api/foo/foo.json:
{
"foo": "bar",
"baz": "bat"
}
/imports/api/foo/Foo.js:
let fooJson = require('./foo.json');
const FooData = {
foo: fooJson.foo,
baz: fooJson.baz
};
export {FooData};
now, on either client or server, you can import FooData:
import {FooData} from '/imports/api/foo/Foo';
... and FooData is available to your JS code.
In Meteor, any resouce file (jpeg, gif, txt, json, etc.) that you wish to make available to the client side must be placed in top level folder called public.
From the client, you can access this data as if it was in the top level (eg. don't include /public). For example, if you had file data.json in /public, you can access it from the browser at /data.json.
Accessing this folder from the server is a bit trickier. I haven't tried this in the latest 1.4 release, but you used to be able to access the public folder like this.
path.join(__meteor_bootstrap__.serverDir, "../web.browser/app");
With that said, you might want to step back a think about why you need the data. If you don't actually need the data in a literal file, then i would put the json on the server only to simplify accessing it there and then serve it to the client via a meteor method.

Categories

Resources