PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 13, 2022

[FIXED] What happens if you send an instance of an ES6 class via REST API?

 October 13, 2022     axios, es6-class, javascript, reactjs, rest     No comments   

Issue

class Data {

  #some_private_var

  constructor(private_val, regular_val) {
    this.regular_var = regular_val
    this.#some_private_var = private_val
  }
}

For example, if I use Axios to make an API request with an instance of the above class as the body of the request, what gets send over to the server?

Will #some_private_var get sent over?

What if a getter method is defined like so:

  get some_private_var() {
    return this.#some_private_var
  }

Solution

Axios by default serialises JavaScript objects via JSON.stringify().

You can easily see what the result of that would be. The behaviour of which is defined here...

All the other Object instances [...] will have only their enumerable properties serialized.

class Data {

  #some_private_var

  constructor(private_val, regular_val) {
    this.regular_var = regular_val;
    this.#some_private_var = private_val;
  }
}

console.log(JSON.stringify(new Data("private", "regular")));

Private properties and methods are not enumerable properties.

If you want to expose members that would otherwise be hidden, create a toJSON() method

If an object being stringified has a property named toJSON whose value is a function, then the toJSON() method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON() method when called will be serialized

class Data {

  #some_private_var

  constructor(private_val, regular_val) {
    this.regular_var = regular_val;
    this.#some_private_var = private_val;
  }
  
  toJSON() {
    return {
      ...this,
      some_private_var: this.#some_private_var
    };
  }
}

console.log(JSON.stringify(new Data("private", "regular")));



Answered By - Phil
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing