简体   繁体   English

从节点/快速路由访问JSON?

[英]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? 我想知道,由于Node是用JavaScript编写的,并且我正在使用ES6编写一个有趣的应用程序,有没有一种方法可以访问我发送到路由的对象,而无需使用ajax从服务器/ 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? 然后能够使用jsonData作为客户端控制器中的变量? 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? 如果没有,我将只使用XHR请求还是获取? Just wondering what my options are since I want to use Node (4.x) to its full potential. 我只是想知道我的选择是什么,因为我想充分利用Node(4.x)的潜力。 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 如果您使服务器端文件在客户端上可用,并且server.js文件具有足够的通用性,使其可以在客户端上运行以及正确的客户端导出语句,那么可以使用如下语法导入jsondata

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

and use it else where 并在其他地方使用

Beware that there are limited browsers that support import statement 请注意,只有少数浏览器支持import语句

You can check the list from here 您可以从这里查看列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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