The object returned by bodyParser is not a string but a data structure

I have been working on implementing a JSON content listener in Typescript using Express and Body-parser. Everything is functioning perfectly, except when I receive the JSON webhook, it is logged as an object instead of a string.

import express from 'express';
import bodyParser from 'body-parser';

// Initializing Express and defining a port
const app = express();
const PORT = 3000;

// Starting Express on the defined port
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

// Basic error handling
app.use((err, req, res, next) => {
  console.log(err.stack);
  console.log(err.name);
  console.log(err.code);
  res.status(500).json({ message: 'Something went wrong' });
})

// Parsing JSON
app.use(bodyParser.json());

// Creating a route (URL set as webhook URL)
app.post('/webhook', (req, res, next) => {
console.log("Headers: " + req.headers.toString());
console.log("Body: " + req.body.toString());
next()
res.status(200).end();
});

The following is returned in the console:

Server running on port 3000
Headers: [object Object]
Body: [object Object]

If I attempt to log the data like this, the value of the "status" key logs correctly:

console.log("Status: " + req.body.status);

Any insights into why this might be happening?

Answer №1

To convert any JSON or JavaScript object (non-circular) to a string, you can use JSON.stringify().

console.log(JSON.stringify(data))

If you are looking to create a route for setting a webhook URL, you can do the following:

// Set up route for webhook URL
app.post('/webhook', (req, res, next) => {
console.log("Headers: " + JSON.stringify(req.headers));
console.log("Body: " + JSON.stringify(req.body));
 next()
res.status(200).end();
});

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

Using Vue.js to connect v-html to a custom CSS stylesheet

I am currently working with HTML generated by a function on an external server and I am able to preview this within a tag. Additionally, I can retrieve the CSS information in a similar manner. <template> <div v-html="html"></div ...

Updating multiple collections in MongoDBRestructuring data across multiple

Imagine a scenario where an API call must update two different collections. It's crucial that if one update fails, the first update needs to be reverted. How can I guarantee that both operations either complete successfully or none at all? Let me prov ...

Generate a new span element within a div element programmatically using Vuex

I have integrated an existing web application developed using vue.js. Below is the code snippet: function () { var e = this, t = e.$createElement, n = e._self._c || t; return e.messag ...

Are the charts missing from the Django admin interface?

I am working on incorporating charts into my admin view by extending the admin/base.html file. Instead of using libraries like charts.js, I prefer to use a template for displaying the charts. Ideally, I want my view to resemble this example (). You can fin ...

Implement a bootstrap modal to pop up upon successful form validation using the formvalidation.io

Dealing with a form that can take a significant amount of time to submit due to posting data to multiple APIs is not uncommon. Normally, I display a message in a bootstrap modal asking the user to wait patiently without clicking the back button. This modal ...

What steps can be taken to hide empty items in a list from being shown?

When I map over an array of books to display the titles in a list, I encounter an issue with the initial empty string value for the title. This causes the list to render an empty item initially. Below is my book array: @observable books = [ {title:" ...

What is the process for converting a date to a string such as "One Days Ago" or "Minutes Ago" in IOS?

I created an application that utilizes JSON parse data. Within this data, there is a date in the format "2014-12-02 08:00:42". I then transform this date into the format "12 FEB 2014" as shown below: NSDateFormatter * dateFormatter = [[NSDateFormatter all ...

What is the best way to handle requests once a SpookyJS script has finished running?

Occasionally, I find myself needing to log in and extract some data from a specific website. To automate this process, I developed a CasperJS script that runs on Heroku. My goal is to create an endpoint like the following: app.get('/test', func ...

The value of the Material UI TextField Input Time Picker remains static and cannot be altered

After using this CodeSandbox example for material UI time picker (https://codesandbox.io/s/5154qzmjl), I am facing an issue where I am unable to change the value of the time. In my code, I have mapped the days array in the state to the TextField: this.st ...

Extract a Key from a JSON Dictionary using Python

I've recently started working on a script as part of my practice routine. The purpose of the script is to take user input and then store it inside a Json file. Here's how the code looks: import json command = int(input("Do You Want To Add, Or Re ...

A guide on manipulating an input field to trigger md-datepicker upon clicking

What is the best way to convert an input text into a fire md-datepicker and achieve a similar result like this? ...

Navigating through Node.js Express 4 routes

As a newcomer to Express 4, I want to keep my question simple. I've been checking out some online tutorials and one thing has left me puzzled. Usually, when setting up Express 4 in app.js, the route code looks something like this: . . var routes = ...

Using Vue 2 with a personalized Axios setup, integrating Vuex, and incorporating Typescript for a robust

I'm still getting the hang of Typescript, but I'm facing some challenges with it when using Vuex/Axios. Current setup includes: Vue CLI app, Vue 2, Vuex 3, Axios, Typescript At a high level, I have a custom Axios instance where I configure the ...

Transmit information to the server via an AJAX request

$.ajax({ url:"http://192.168.0.74:8080/pimsdesign/JSONRequestHandler" , type: "POST", data: {name: "amit", id:1 }, dataType: "json", beforeSend: function(xhr) { if (xhr && xhr.overrideMimeType) { xhr.overrideMimeType("application/json;charset=UTF-8 ...

Angular correctly displaying specific array items within button elements

I am facing an issue with my dashboard where I have 4 items in an array and 4 buttons on display. My goal is to assign each item with a specific button, but currently, it shows 4 buttons for each "hero" resulting in a total of 16 buttons. I have tried usin ...

Rules for specifying title attribute for tag a in JavaScript

What is the best way to handle conditions for the a tag (links) when it has content in the title attribute? If there is no description available, how should the script be used? For instance: if ( $('a').attr('title') == 'on any ...

Parse the JSON response, extract specific keys, and transform them into a CSV format

Reading keys from generated json from REST API without pandas installed on server and with Python version 2.6.6. Data is being loaded from a file using json.load : import json with open('response.json','r') as f: data = json.load ...

Prevent automatic scrolling to anchors when using router.push() in Next.js

When using the latest version 10.2 of next, every time a URL with a hash is pushed to the router, next.js automatically jumps to the anchor element. import {useRouter} from 'next/router' router.push('/contact#about-us'); This behavior ...

Trigger a refresh of the Angular app by clicking a button

Recently, I embarked on developing a single-page application that allows users to input data in a text box and navigate to another page. While designing the second page, I aimed to incorporate a home button that would not only return me to the initial view ...

Having trouble signing out in Nextjs?

As a newcomer to Reactjs and Nextjs, I am currently working on developing an admin panel. To handle the login functionality, I have implemented the following code in my index.js/login page using session storage: const data = { name: email, password: pa ...