首页 > 解决方案 > 通过 express 发送带有其父类的对象

问题描述

我想知道是否有任何方法可以从快递服务器发送对象,然后instanceof在接收端检查该对象。

我正在为 express 编写集成测试,并想检查instanceof响应正文的。可悲的是,原型丢失了(我的猜测是它丢失是由于stringifyand 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

标签: javascriptnode.jsexpress

解决方案


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

真的不确定这是否适用于您的用例……这似乎是一件奇怪的事情。测试实际行为而不是具体实现可能会更好。


推荐阅读