javascript - 通过 express 发送带有其父类的对象
问题描述
我想知道是否有任何方法可以从快递服务器发送对象,然后instanceof
在接收端检查该对象。
我正在为 express 编写集成测试,并想检查instanceof
响应正文的。可悲的是,原型丢失了(我的猜测是它丢失是由于stringify
and parse
)。
澄清:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const request = require('request');
app.use(bodyParser.json());
app.use(bodyParser.text());
app.use(bodyParser.urlencoded({ extended: true }));
class ParentClass {
constructor(name) {
this.name = name;
}
};
class ChildClass extends ParentClass {
constructor(name, age) {
super(name),
this.age = age;
}
}
app.get('/', (req, res) => {
let myChild = new ChildClass('test', 21)
res.json(myChild)
});
server = app.listen('3005', '0.0.0.0');
request.get(`http://localhost:3005`, (err, response, body) => {
console.log(JSON.parse(body) instanceof ParentClass)
})
body
打印出来的是:
name: 'test',
age: 21,
__proto__: Object
我的最终目标是该行将body instanceof ParentClass
返回true,但目前它返回false。
解决方案
HTTP 请求返回一个字符串,在这种情况下是您对象的字符串化版本。这不会保存有关 javascript 类的任何数据,因此您将无法instanceof
在接收端使用,因为它只是一个字符串。
您可以做的一件事是向您的基类添加一个属性,将其原型链编译成一个数组,然后您可以简单地检查您要查找的类名是否在该数组中。
class ParentClass {
constructor(name) {
this.name = name;
// build class chain
this.classes = []
let p = Object.getPrototypeOf(this)
while (p) {
this.classes.push(p.constructor.name)
p = Object.getPrototypeOf(p)
}
}
};
class ChildClass extends ParentClass {
constructor(name, age) {
super(name)
this.age = age;
}
}
let myChild = new ChildClass('test', 21)
// has classes property that will be stringified
let childString = JSON.stringify(myChild)
console.log(childString)
// on the client side
let obj = JSON.parse(childString)
console.log("Instance of Parent?", obj.classes.includes('ParentClass')) // instaed of instanceof
真的不确定这是否适用于您的用例……这似乎是一件奇怪的事情。测试实际行为而不是具体实现可能会更好。
推荐阅读
- c - 如何反转C中的句子?
- paypal - 什么是 Paypal 的定期付款配置文件 RPSTATE 参数?
- postgresql - 更改 client_min_messages 和 log_min_messages
- python-3.x - 您如何比较包含不可散列对象的字典?
- c - 字符串计数问题、浮点整数、基于字母、单词和句子数量的评分公式,在 C 中
- jquery - 选中复选框时选择特定的单选选项jQuery
- c# - 如何声明一个完全限定的路径来实例化一个对象?
- r - 使用 R 跨多个数据集通过重复和交叉引用过滤 FEC 数据
- networking - 您如何使用 Wireshark 识别某些 TCP 段的确认?
- typescript - 在保持 CommonJS 格式的同时转换到 TypeScript