[英]How to send JSON inside of class syntax to an 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數據發送到class syntax
內部的API中,但是每次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'));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.