What is the best method for converting text to json in an express server using bodyParser?

I am currently working with an express server that is serving as an API. The main.ts file, where the server is set up, looks like this:

const app = express();

app.use(bodyParser.json({ type: "application/json" }));
app.use(bodyParser.text({ type: "text/plain" }));
app.use('/', routes);

app.listen(8080, () => {});

The routes object contains a GET definition as follows:

routes.get('/myObject', (request: Request, response: Response) => {
    console.log(request.body); // Output : {}
});

Recently, I encountered an issue where the request body sent from another server is not being parsed correctly.

Here is the XHR request being sent from the second server:

    const request: XMLHttpRequest = new XMLHttpRequest();
    request.open("GET", "http://localhost:8080/myObject");
    request.setRequestHeader('Accept', 'application/json');
    request.setRequestHeader("Content-Type", "text/plain");
    request.setRequestHeader('Access-Control-Allow-Origin', '*');
    request.onload = () => {
        console.log(request.status);
    };
    request.onerror = (err) => {
        console.log(request.status);
    }
    request.send(JSON.stringify({ "key": "value" }));

However, when I view the data on my express server, it only shows an empty object {} instead of { "key": "value" }. Any insights on what might be causing this issue?

Additionally, if the data appears in the format "{\"key\":\"value\"}" on the express server, is there a way to implicitly convert it into a JSON object for the request.body?

Answer №1

Try switching the method to POST instead of GET and see if that works. GET responses have their body set to null.

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

JSX is a powerful tool that revolutionizes the way we structure our front-end components. One of the most

I'm currently facing an issue while attempting to create a custom component that utilizes a looping array to conditionally render different elements. In this component, I have special classNames that help generate a grid with 3 elements per row, regar ...

The total number of rows in each section is determined by the count specified in the "numberOfRowsInSection

When attempting to configure this segmented table to showcase different JSON arrays in separate sections, I encountered an issue where having a larger row count in any section following the first resulted in the error message: [__NSArrayM objectAtIndex:]: ...

How can I restrict access to localhost:3000 so that only my device can access it within the network?

Currently, I am utilizing express.js for hosting an HTTP server. Is there a method available to restrict access to port 3000 through my IP address for other devices on the network? ...

Launching Angular 2 Application on Azure Cloud

I have recently been diving into the world of Angular 2 and Azure. Following the steps outlined in the Angular 2 Tutorial, I was able to successfully run my application locally without any issues. After deploying the app to Azure, I encountered a problem. ...

What is the best way to display a varied value from my array during each loop of my function?

Hey all, I'm working with a function called drawgrowingpie that includes a segment function for drawing pie charts (from an example on raphaeljs.com). My goal is to assign a unique color to each segment of the chart using an array called clr. However, ...

Ways to pause YouTube video when hiding a Div

Although I've asked a similar question previously, I am revisiting the issue as I have since taken a different approach. My previous attempts with the YouTube API were fruitless, so I am exploring new options. My goal is to create a website where var ...

Converting dates in Javascript

I have retrieved a date/time value of "20131218" from an API response. My goal is to transform this date into the format "2013-12-18". In PHP, this can be easily achieved with the following code: echo date("Y-m-d", strtotime('20131218')); The ...

Handling exceptions in the event that the backend URL resource cannot be accessed

I'm facing an issue with my Vue.js single file component where I am trying to catch exceptions when the URL requested by axios.post is unreachable. I have encapsulated the entire code in a try block, but for some reason, the alert in the catch block i ...

Use CodeMirror on an existing div element

My div named "content_editable" is the center of my code editing application. I need it to adhere to specific CSS dimensions, but I also want to integrate CodeMirror syntax highlighting into it. However, following the documentation's instructions does ...

Decompressing and reading a compressed (GZ) JSON file in PHP

Thanks to the brilliant minds over at Stackoverflow, I have successfully learned how to extract JSON data from a file and store a 'Value' in a database. The only issue is that the file I need to read from is an enormous 2GB file, which my web se ...

Angular: Keeping all FormControls in sync with model updates

I am dealing with a collection of FormControls that were created using FormBuilder: this.someForm = this.fb.group({ name: '', size: '', price: '', }); Is there an alternative method to update them based on ...

Using the immutable update pattern with nested data in React

In Redux, it is emphasized that in order to update nested data, every level of nesting must be copied and updated appropriately. // changing reference in top level const newState = {...oldState} newState.x.y.z = 10; setState(newState) // or updating refer ...

Struggling to determine whether an array contains data or is void in ReactJS?

In the state, I have an array and I set the default value of my state to an empty array []. After loading an API request, I need to display a loader until the data is ready. So, I am using a condition like this: (if the array length === 0, the loader wil ...

Encounter AttributeError: 'str' does not contain method 'read' while attempting to display information from a JSON data file

I'm struggling to extract and display specific data from a JSON file. While attempting to print all the data, I encountered an error message saying "AttributeError: 'str' object has no attribute 'read'". def jsonParser(file): w ...

After running javascript, Elements do not retain any values

I have encountered an issue with two button click events - one is in Javascript and the other in VB. The first button (Javascript) retrieves values from various controls like textboxes and dropdown lists, while the second button (VB) saves these values to ...

Is there a way to determine the items that will be displayed on this page by clicking a link from a different page?

First Page: Whenever a link is clicked, it will redirect to the second page where only the relevant item will be displayed <ul class="portfolio-filters list-inline"> <li ><a href="page2.html/#webdesign-filter">Web ...

What is the process for adding a Contact Us page to a website?

I recently created a website using html, css and Javascript. I would like to include a 'get in touch' page where visitors can send me messages directly on the site. What steps should I take to make this happen? Is it necessary to set up a databas ...

Encountering a Cannot GET error when using Express routing with parameters:

I've encountered a "Cannot GET" error while attempting to use express routing with parameters for the first time, and I'm puzzled as to why. Everything was working smoothly until I installed lodash, and now nothing seems to work anymore. Here&a ...

What is the reason that the Mongoose updateMany() function only functions properly when combined with .then

Currently delving into the intricacies of Mongoose, I am perplexed as to why updateMany() requires a .then() at the end in order to be executed. For instance, here is the snippet that I'm endeavoring to execute, with the intention of altering the rat ...

Creating an Efficient React Portal Component

Having trouble rendering an input field within a portal. Whenever I change the value of the input, it loses focus. I suspect this is happening due to re-rendering upon state change. Link to code sandbox Any suggestions for a solution? UPDATE Is there a ...