CodexBloom - Programming Q&A Platform

AJAX call to React app with Axios returning incorrect data format from Node.js backend

πŸ‘€ Views: 2 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-05
ajax axios react node.js express JavaScript

I'm collaborating on a project where I'm deploying to production and I'm working on a React application that makes an AJAX call to a Node.js backend using Axios... I've configured the backend to return data in JSON format, but I'm getting an unexpected output in my frontend. The request is sent successfully, but the response seems to be wrapping the JSON object in an additional layer. I'm using Axios version 0.21.1 and Express version 4.17.1 on the backend. Here’s the code from my React component where the AJAX call is made: ```javascript import React, { useEffect, useState } from 'react'; import axios from 'axios'; const MyComponent = () => { const [data, setData] = useState(null); useEffect(() => { const fetchData = async () => { try { const response = await axios.get('http://localhost:5000/api/data'); setData(response.data); } catch (error) { console.error('Error fetching data:', error); } }; fetchData(); }, []); return <div>{JSON.stringify(data)}</div>; }; export default MyComponent; ``` On the backend, my Express route looks like this: ```javascript const express = require('express'); const app = express(); app.get('/api/data', (req, res) => { res.json({ message: 'Hello, World!', success: true }); }); app.listen(5000, () => { console.log('Server is running on http://localhost:5000'); }); ``` When I check the network tab in my browser's developer tools, I see that the response is wrapped like this: ```json { "data": { "message": "Hello, World!", "success": true }, "status": 200, "statusText": "OK", "headers": {...}, "config": {...}, "request": {...} } ``` I was expecting just the inner object (`{ message: 'Hello, World!', success: true }`). I've tried checking the Axios configuration and even used `.then` to handle the response, but I'm still getting the same result. Is there something I'm missing in the way Axios handles the response? Any insight on how to correctly retrieve just the data I need would be greatly appreciated. My development environment is Ubuntu 20.04. Am I missing something obvious? This is my first time working with Javascript latest. Any examples would be super helpful. I'm developing on macOS with Javascript. Any ideas how to fix this?