javascript - 如何将类语法中的 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?
解决方案
我想这就是你想要的?
// 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'));
推荐阅读
- nominatim - Nominatim:按门牌号和邮政编码搜索
- android - 在没有 addToBackStack 的情况下,当前 Fragment 是否在每个 Replace 事务中被销毁?
- python - 将 SHAP 汇总图另存为 PDF/SVG
- php - SQL查询跳过PHP for循环中的行
- javascript - 隐形 ReCapcha 不调用回调
- sqlite - Ionic 3 SQLite:SQLiteObject 的方法 executeSql() 不起作用
- angular - Angular 2 - 在服务中创建警报
- android - 如何使用 Kotlin 访问 Firestore 中的组件?
- r - 每次加载包时从互联网下载新数据
- python - 将大型 JSON 数组写入文件