首页 > 解决方案 > 如何将类语法中的 JSON 发送到 API?

问题描述

假设我有一个普通mjs文件和一个这样的 API:

// Storage.mjs
class Storage {
    constructor(name, age) {
        this.name = name;
        this.age = age;
        this.json = JSON.stringify(this);
    }
}
var store = new Storage('eMart', 2);

// server.js
var express = require('express'),
    fs = require('fs'),
    data = fs.readFileSync('website/js/storage.mjs'),
    convert = JSON.parse(data);

var app = express(),
    server = app.listen(3000, initialize);

console.log(convert);

function initialize() {
    console.log("Local Host Initialized.");
}

app.use(express.static('website'));

我的目标是将 JSON 数据发送到内部的 API class syntax,但每次 Node 不断抛出undefined并出现像这张图片一样的错误;

在此处输入图像描述

大多数人的问题是将数据从 API 发送到特定js文件,这与我的情况完全相反。很难从那里找到解决方案。

是否有任何适当的方法可以将 JSON 数据传递给 API?

标签: javascriptnode.jsapivariablesrouter

解决方案


我想这就是你想要的?

// assume this is loaded with fs.readFileSync
const mjs = `
class Storage {
    constructor(name, age) {
        this.name = name;
        this.age = age;
        this.json = JSON.stringify(this);
    }
}
var store = new Storage('eMart', 2);  // I assume you missed the quote here
`;

eval(mjs);  // You can't just convert an js file into a JSON, you have to eval it first(not safe, use it with caution)

let result = JSON.parse(store.json);  // Since the file outputs a variable called "store" and it has a "json" property

console.log(result);

server.js片段_

// server.js
var express = require('express'),
    fs = require('fs'),
    data = fs.readFileSync('website/js/storage.mjs');  

(0, eval)(data);  // indirect eval
var convert = JSON.parse(store.json);

var app = express(),
    server = app.listen(3000, initialize);

console.log(convert);

function initialize() {
    console.log("Local Host Initialized.");
}

app.use(express.static('website'));

推荐阅读