When I send data using axios, I receive the response in the config object instead of the data

Currently, my web app is being developed using NextJS NodeJS and Express. I have set up two servers running on localhost: one on port 3000 for Next and the other on port 9000 for Express.

In the app, there is a form with two input fields where users can enter their data. When the form is submitted, the state is sent via axios post to a specific URL. On the server-side, this request is received and the same data is sent back as a response.

Upon receiving the response from the server, the data is provided in config.data along with a message indicating success.

I am trying to figure out why the data is nested within config data and how I can extract it from this JSON object so that I can assign it to a variable.

My attempts to extract the data from config.data using for loops have not been successful as they either populate an array with 56 elements or do not yield any results.

On the client side:

state = {
  bank_name: '',
  account_number: ''
}

...

onSubmit = (e) => {
  e.preventDefault()

  axios.post('http://localhost:9000/api/bank', {
    bankName: this.state.bank_name,
    accNumber: this.state.account_number
   })
    .then(res => {
      console.log(res)
    }).catch(err => console.log(err))
  }

Server side implementation:

router.post('/', (req, res) => {
    const {reqData} = req;
    res.send(reqData);
})

Output of console.log(res) on the client side:

{
  config: {
    url: "http://localhost:9000/api/bank",
    method: "post",
    data: '{"bankName":"some new bank","accNumber":"39276542934235"}'
  },
  data: "success",
  headers: "...",
  request: "...",
  status: 200,
  statusText: "OK",
  __proto__: Object
}
...

Trying to access res.config.data.bankName returns undefined.

It seems like the issue might be related to the format of the server response, potential parsing errors, or promises handling.

If you have any insights or suggestions, they would be greatly appreciated. Thank you!

Answer №1

Ensure that the res.config.data is a string, if not, parse it using JSON.parse(res.config.data) before accessing the bankName.

Additionally, confirm that you are utilizing body-parser on the express side. As the post data is stored in req.body, make sure to send that back instead of the entire req object.

Express:

router.post('/', (req, res) => {
    const reqData = req.body;
    return res.send(reqData);
});

Axios: (retrieve returned data from res.data)

axios.post('http://localhost:9000/api/bank', {
    bankName: this.state.bank_name,
    accNumber: this.state.account_number
})
.then(res => {
    console.log(res.data);
}).catch(err => console.log(err))
}

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

Navigating state: (TypeError): The mapping function for this.state.[something] is invalid

I am currently working on iterating through my state, which contains data retrieved from an external API. However, I encountered this error message: TypeError: this.state.stocks.map is not a function My goal is to display the results on the frontend dyn ...

Having trouble executing Token-based authentication-passport code in NodeJS and ExpressJS

app.js const express = require('express'); const path = require('path'); const logger = require('morgan'); const app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app ...

What is the best way to transfer static assets from an npm package to a nuxt project?

Has anyone successfully sent assets from an npm package to a nuxt application before? I have a vue component within an npm package with the following structure: -src/ -assets/ -noun-filter.svg In this npm package, the vector image is included in the v ...

Bidirectional data flow in AngularJS Directives

In an effort to create a dynamic form with different "widgets" based on field types and parameters stored in a database, I have been exploring directives for handling layout changes in response to various scenarios. After experimenting with some examples, ...

The installation of npm encountered an error. For a detailed log of this process, please refer to the complete log file within the

I am encountering issues with installing the react app. After running npm install, I am receiving multiple errors in the terminal. npm ERR! code 1 npm ERR! path C:\Users\Yaya\Desktop\ATL\detexter-web-front\node_modules\no ...

Choose information based on the prior choice made

Using the Material UI Stepper, I have a task that involves setting conditions based on the selection of checkboxes. In step one, there are two checkboxes - Individual and Bulk. In step two, there are also two checkboxes - First Screening and Second Screeni ...

Enhance the appearance of the <td> <span> element by incorporating a transition effect when modifying the text

I need help with creating a transition effect for a span element within a table cell. Currently, when a user clicks on the text, it changes from truncated to full size abruptly. I want to achieve a smooth growing/scaling effect instead. You can view an exa ...

What is the best method to position images in the same way as seen in the screenshot

Any tips on aligning images shown in the screenshot? Please note that the images will be from the backend. https://i.stack.imgur.com/LnYLM.jpg I experimented with code to position images using top, right, left, and bottom properties, but it becomes cumb ...

Steps to successfully implement onClick functionality in html within C# server side code

I'm having trouble with my onClick function. When I click, nothing happens and there are no errors to help me diagnose the issue. var data = new FormData(); data.append("cart_list", new_cart); $.ajax({ url: "@Url.Action ...

Internet Explorer: JQuery deselects radio button upon its selection

One issue I have encountered is with a listener for a group of radio buttons in IE. When a radio button is selected, it triggers a database call to populate a select element. However, in IE, after the code runs successfully, the selected radio button becom ...

When trying to save an image using multer's storage, the error message "ENOENT: file or directory not found" is displayed. It is important to note that symbols are not causing

Whenever I try to save an image using multer's storage feature, I encounter the following issue: [Error: ENOENT: no such file or directory, open 'C:\MAMP\htdocs\Chat Backend\public\images\servers\1596819056816AF ...

Verify the mining share in NodeJS prior to sending it to the pool (Stratum)

Struggling to verify if a share meets the minimum difficulty requirement. I have all the necessary data to generate a block hash and compare it with the difficulty level. However, my code is failing to produce a valid block hash, and I can't pinpoin ...

Is there a way to gradually reveal JSON data without continuously re-parsing and displaying it on a webpage?

Currently, I am working with a log file that is constantly updated by a running script in real-time. My goal is to effectively monitor the status of this script on a web page using HTML and JavaScript. To achieve this, I have utilized JavaScript to dynamic ...

Make sure to prevent losing the global status in Vuex and VueRouter when the page is refreshed

As I develop a Single Page Application (SPA), I am utilizing Vuex to manage session states on the client side. However, I have noticed that the state resets whenever the browser is manually refreshed. Is there a way to prevent this behavior without relying ...

angularjs Populate input fields with default values within ng-repeat loop

Our challenge is to display input text with pre-filled values within a list using the ng-repeat directive. <ul ng-repeat="post in postList> <input type="text" ng-model="postid" nginit="postid='{{post.id}}'"></input> </u ...

What causes the react-beautiful-dnd draggable items to be scattered everywhere when dragged?

Currently, I am utilizing react-beautiful-dnd, MUI, and Next.js in my project. Although the example code appears to be very simple, it is not functioning as expected. Instead, it displays as shown in this image: https://i.stack.imgur.com/Y9kye.gif ...

Tips for incorporating the "define" function into your Mocha testing

Starting my journey with JavaScript testing, I made the decision to use Mocha. The specific modules I am looking to test are AMD/RequireJS. However, it appears that Mocha only works with CommonJS modules. Consequently, when trying to run it, I encounter t ...

Removing directories on Cloudinary using an array of directory names

Can folders be deleted by an array of their names without the need for looping? Is there a method that allows something like this? const folderNames = [folder1, folder2, folder3, folder4]; cloudinary.api.delete(`folder/subfolder/${foldersNames}`)}); ...

Is there a method for uploading and viewing files from a server using the MERN stack?

Looking to create a functionality for users to upload various file types such as documents, presentations, and text files, save them to a database, and then view them from the server. Are there any recommended frameworks or npm modules to help with this ...

Is jest the ideal tool for testing an Angular Library?

I am currently testing an Angular 9 library using Jest. I have added the necessary dependencies for Jest and Typescript in my local library's package.json as shown below: "devDependencies": { "@types/jest": "^25.1.3", "jest": "^25.1.0", ...