简体   繁体   English

如何将类语法内的JSON发送到API?

[英]How to send JSON inside of class syntax to an API?

Let's say I have a normal mjs file and an API such as this: 假设我有一个普通的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'));

My goal is to send the JSON data to API which is inside of class syntax , but every time Node keeps throwing undefined and an error like this picture; 我的目标是将JSON数据发送到class syntax内部的API中,但是每次Node抛出undefined的错误和类似此图片的错误时,都不会发生。

在此处输入图片说明

Most of people's question was sending data from API to specific js file which was totally opposite of my case. 大多数人的问题是将数据从API发送到特定的js文件,这与我的情况完全相反。 It was hard to find solution from there. 从那里很难找到解决方案。

Are there any proper ways to pass JSON data to API? 是否有将JSON数据传递到API的适当方法?

I suppose this is what you want? 我想这就是你想要的吗?

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

The server.js snippet 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'));

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

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