简体   繁体   中英

Accessing JSON from Node/Express Route?

I was wondering, since Node is written in JavaScript, and I'm using ES6 to write a little fun app, is there a way to access the object I send to the route without using ajax to get it from the server/api? In other words, can I say something like

import { jsonData } from '../api/server.js'; 

and then be able to use jsonData as a variable in my client side controller? In other words... I would have something like this:

var DataController = (req, res) => {
let data_client = new DataClient();

data_client.getData().then(
    (data) => {
        res.render('index', { jsonData: jsonData });
    },
    (error) => {
        res.send('An error occurred. Please check your connection settings.');
    }
);

Is what I'm asking possible? If not, would I just use an XHR request or fetch? Just wondering what my options are since I want to use Node (4.x) to its full potential. Sorry if this question was confusing or vague.

I don't think that server side file will be accessible over client side.

If you make your server side file available on client and your server.js file is generic enough to run on client side as well along with correct client side export statement , then yes you can import the jsondata with syntax like

import { jsonData } from '../api/server.js'; 

and use it else where

Beware that there are limited browsers that support import statement

You can check the list from here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM