Using express version 4.x to send an empty JSON object

I'm struggling with returning an object in JSON format using Express. What's confusing me is the following code snippet:

class Greeting {
  Greeting(name) {
    this.name = name;
  }
  get name() {
    return name;
  }
}

app.get('/json/:name', function (req, res) {
  greeting = new Greeting(req.params.name)
  greeting.something = req.params.name
  res.json(greeting)
})

http://localhost:3001/json/someparam

Output:

{
"something": "someparam"
}

Why is the name set in the constructor not being returned as well?

Answer №1

retrieve name() { return name; }

name is not clearly defined in this context, so attempting to access

greeting.name

will result in a syntax error. Even if you were to correct this error, getters are not included in an object and will not be serialized, leading to the expected behavior. Removing this unnecessary getter entirely will align with your intended functionality. An additional oversight is that in JavaScript, the constructor is referred to as constructor.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered while running a mounted hook in Vue.js that was not properly handled

I have created a To Do List app where users can add tasks using a button. Each new task is added to the list with a checkbox and delete button next to it. I want to save all the values and checked information on the page (store it) whenever the page is ref ...

Boost the elements' worth within an array

Assume I am working with an array shown below... let myArr = [0,0,2,0,0]; I am aiming to generate a ripple effect where the modified array becomes [0,1,2,1,0] ...

Streamlining the process of implementing click events on elements selected by class using jQuery

Slowly but surely, I am gaining familiarity with jQuery and have reached the point where I desire to abstract my code. However, I am encountering issues when attempting to define click events during page load. Within the provided code snippet, my objectiv ...

Dynamic HTML text colors that change rapidly

I have an interesting question to ask... Would it be possible to create text that switches between two colors every second? For example, could the text flash back and forth between red and grey? I don't mean changing the background color, I mean act ...

When using the `mongoose find()` method, the returned _id may not match the one stored in

Just had a bizarre experience while working with MongoDB recently. It appears that when I make a query in a collection for a document, instead of returning the _id stored in the database, it generates a new _id for the queried document. For instance: In ...

Perpetual duplication of data occurs upon inserting an item into the Array state of a React component

Whenever a new item is added to the React JS Array state, data duplication occurs. console.log(newData) The above code outputs a single object, but when you print the actual data with console.log(data) You will notice continuous duplicates of the same da ...

"Unable to get elements by tag name using the getElementsByTagName method in

function updateLayout() { var para = document.getElementsByTagName("p"); para[0].style.fontSize = 25; para[1].style.color = "red"; } <p>Text in paragraph 1</p> <p>Text in paragraph 2</p> <p>Text in paragraph 3</p& ...

What is the best way to filter and sort a nested tree Array in javascript?

Looking to filter and sort a nested tree object for a menu If the status for sorting and filtering is true, how do I proceed? const items = [{ name: "a1", id: 1, sort: 1, status: true, children: [{ name: "a2", id: 2, ...

Capture the JSON data and save it into a separate JSON file

Just starting out with JSON and using an ajax call, I've managed to retrieve a JSON object with the following structure: { data: [ { bouquet: "Interactive", list: [] }, { bouquet: "Movie ...

Utilizing THREE.JS Raycaster with JavaScript "entities" rather than just meshes

I am facing a challenge with the Raycaster model. I grasp the concept of how it intersects meshes that can be transformed, but my issue lies in identifying when the specific instance of an object is clicked. Consider a scenario where there is a button. Th ...

What steps should I take to resolve the issue with running npm start?

I am encountering an issue while using React and trying to run my application. When I execute "npm run start," I receive the following error message: npm ERR! Missing script: "start" npm ERR! npm ERR! Did you mean one of these? npm ERR! npm star # Mark ...

Retrieving form data in controller and model through route

Within my app.js file, I am passing the request to the router in the following manner: app.post('/validateUser', validationRoute) In my route, I typically pass the request on to the controller like this, to call the appropriate function: router. ...

Can Express Handlebars be used solely for rendering a partial without including a layout?

I have successfully configured express handlebars with the following folder structure: views/ layouts/ partials/ User Search Partial HTML (located in views > partials) <div id="user-search"> <h1>Search Users</h1> </ ...

Storing JSON data in an SQLite database involves creating a table with a

I'm having trouble figuring out how to save data in 'JSON' format into my sqlite database for a Rails application. I've looked into various methods, but so far haven't found any promising solutions. Can anyone provide guidance on h ...

Conceal the slider thumb within the material-ui framework

I've been attempting to conceal the slide thumb, initially without using a library. However, I started considering utilizing material-ui as it might make the process easier. Hence, I'm seeking assistance here. Below is my code snippet: import * ...

Rendering dynamic HTML content using EJS

I've created a blog application using Express and MongoDB, with EJS for rendering the data. My issue lies in the styling of the content to resemble a paragraph: <div class="show-post__content"> <%= post.body %> </div> The po ...

Leveraging NodeJS/express for efficient caching and optimizing 304 status codes

Upon reloading a website created with express, Safari displays a blank page (unlike Chrome) due to the 304 status code sent by the NodeJS server. How can this issue be resolved? While it could potentially be a problem with Safari itself, the fact that ot ...

In relation to the Uncaught Error: Syntax error, an unrecognized expression has been encountered

Recently, I started working on an AngularJS and Node.js application. It's all new to me. In the HTML page, I defined a link as <li><a data-toggle="modal" data-target="#myModal" href="/#/login">Login</a></li>, and then set up th ...

Unable to remove the "d-none" class using Bootstrap 4

Wondering if it's possible to remove the "d-none" class using JavaScript? This is the code snippet I currently have: <div id="progressBar" class="progress d-none"> <div class="progress-bar" role="progressbar" aria-valuenow="0" aria- ...

Break down a string into an array containing a specific number of characters each

I'm currently working on a project that involves tweeting excerpts from a book daily via a small app. The book's content is stored in a text file and I need to split it into 140-character-long strings for posting. Initially, I tried using the s ...