简体   繁体   中英

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:

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

在此处输入图片说明

Most of people's question was sending data from API to specific js file which was totally opposite of my case. It was hard to find solution from there.

Are there any proper ways to pass JSON data to 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
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'));

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