The response from a post request in Reactjs using axios is coming back empty

When working on my Reactjs app, I am using axios.post() to edit a mysql database on the backend. The data is successfully sent through the post request to the backend. However, I am facing an issue where I need to determine when the post request has finished and receive some data from it to ensure that the backend code executed correctly. Below is the code snippet I've tried, with newEdit being an object containing necessary information for the backend:

axios
 .post('http://ip:3001/edit_table', newEdit)
 .then((response) => { 
     console.log("response: ", response);
 }, (error) =>{
     console.log("error: ", error);
 });

Despite the successful transfer of the object to the nodejs file, neither of the console log statements are executed. I am unable to get any type of response. Can anyone help me troubleshoot this issue? Thank you.

Answer №1

If your backend code is functioning correctly and returning a response, you can use the example below to update data seamlessly.

const updateData = async () => {
            try {
                const response = await axios.put(`https://jsonplaceholder.typicode.com/posts/${id}`, {
                    method: 'PUT',
                    body: JSON.stringify({
                        id: id,
                        title: post.title,
                        body: post.body,
                        userId: 1
                    }),
                    headers: {
                        "Content-type": "application/json; charset=UTF-8"
                    }
                })
                    .then(response => response.json())
                    .then(json => console.log(json));
                console.warn(response.data);
            } catch (error) {
                console.warn(error);
            }
        };

Answer №2

Ensure that your server-side is sending a response back to the client. You have the option to utilize either res.send or res.json. The method res.send([body]) is utilized for sending an HTTP response to the client, while res.json(body) is used for sending a JSON response.

res.send([body])

res.send(new Buffer('hooray'));
res.send({ example: 'json' });
res.send('<p>some more html</p>');

Example:

var express = require('express')
var app = express()

app.get('/', function (req, res) {
    res.send('hello universe')
})

app.listen(3000)

res.json([body])

res.json(null)
res.json({ user: 'sally' })
res.status(500).json({ error: 'statement' })

Example:

var express = require('express')
var app = express()

app.get('/', function (req, res) {
    res.json({ done: true })
})

app.listen(3000)

References:

Express API reference

Information on Node.js response object methods can be found at res.send and res.json

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

Webpack: Failure to Locate Node Modules

Today while working with webpack, I encountered an issue where it was unable to resolve common node modules like fs and inspect. Upon investigating, I came across a helpful solution on GitHub which suggested setting the modules to none through webpack&apos ...

What are your thoughts on the practice of utilizing the useState hook within a component to send data to its parent component?

I have been working on developing an Input component that can be dynamically used in any page to store input values. The component also includes an attribute called getValue, which allows the parent component to access the input value. In my App.js file, I ...

The second Node.js application on my Nginx server is unable to connect to the newly configured port

I currently have 2 node apps running on Nginx with pm2. One was configured in cluster mode, and the other in fork mode with only one instance. My goal is to have one app listen on port 3000 and the other on port 4000. In my nginx.conf file, I have the foll ...

The combination of Google App Engine API with a static architecture is a powerful

Currently in the process of figuring out the optimal way to structure a JavaScript client + NodeJS server application for hosting on Google Cloud AppEngine (along with potential use of other GCP resources). Seeking advice and best practices in this regard. ...

Design an element that stretches across two navigation bars

Currently, I have implemented two Navbars on my website as shown in the image below: https://i.stack.imgur.com/4QmyW.png I am now looking to include a banner that clearly indicates that this site is a test site. In addition, I would like to incorporate a ...

When using Bcrypt compare(), the result is consistently incorrect

After implementing this code for comparison, I encountered an issue with the compare password functionality. UserSchema.pre('save', async function() { const salt = await bcrypt.genSalt(10) this.password = await bcrypt.hash(this.password, ...

Tips for extracting text from nested elements

I have a collection of available job listings stored in my temporary variable. I am interested in extracting specific text from these listings individually. How can I retrieve text from nested classes? In the provided code snippet, I encountered empty lin ...

What is the significance of the .bin folder located within the node_modules directory? And, could you explain

Why is the .bin directory present in the node_modules folder? In a different discussion on Stack Overflow, it was mentioned that: "it's where your binaries (executables) from your node modules are located." Furthermore, could someone elaborate on t ...

Utilizing SequelizeJS to incorporate related data through primary keys

Currently, I am working on developing a REST API using SequelizeJS and Express. While I have experience with Django Rest Framework, I am looking for a similar function in my current setup. The scenario is that I have two tables - User and PhoneNumber. My ...

NodeJS is not searching for an index.js file

My Node.js server is having trouble locating the module unless I specifically mention that I am searching for the index.js file. For example: When I don't specify the index.js: When I do specify the index.js (it doesn't find the index.js inside ...

The React task list updates the todo items on change, rather than on submission

As a newcomer to React, I have embarked on the classic journey of building a todo app to learn the ropes. Everything seems to be functioning smoothly except for one minor hiccup: When I input a new todo and hit "submit", it does get added to my array but d ...

Having trouble with running Ionic serve in your Ionic 2 project?

While running the command `ionic serve` in node.js command line or GitHub power shell, I encountered the following error: There is an error in your gulpfile: Error: `libsass` bindings not found. Try reinstalling `node-sass`? at getBinding (D:\Git ...

The socket.on() function is not able to receive any data

I am encountering an issue with implementing socket.on functionality $('#showmsg').click(function() { var socket = io.connect('http://localhost:3000'); var msgText = $('#msgtext'); socket.emit('show msg', msgText.va ...

The challenge of website sizing issues with window scaling and the overlooked initial-scale value in HTML

After encountering sizing issues on Windows 10 due to default scaling set at 125%, I attempted to replicate the issue by adjusting the Scale on Ubuntu. My attempt to fix the size by modifying the initial-scale value did not yield any results: document.que ...

Updating the state in a different component using React and Typescript

The Stackblitz example can be found here I'm attempting to update the useState in one component from another component. Although it seems to work here, it's not functioning properly in my actual application. Here is a snippet of the app.tsx co ...

Using Socket.IO in Node.js to distribute information to every connected client

Currently, I am in the process of developing a WebGL multiplayer game. My approach involves using socket.io and express in node.js to enable multiplayer functionality. However, I am encountering an issue with broadcasting key events. When a user presses a ...

Leveraging jsonp with nodejs and original ajax

I wanted to understand how jsonp works, so I decided to create a demo using nodejs without jQuery. However, I encountered some issues with my code. Here is what I tried: views/index.jade doctype html html head title Demo of jsonp body #res ...

JShint malfunctioning

My attempt to install jshint using npm with the command npm install -g jshint didn't seem to work correctly. Even after I reinstalled node due to previous issues, running the command again yielded no results in the terminal. The output from my install ...

Utilizing React to modify the functionality of elements in the user interface depending on the size of

In this section, I will provide details about my current project. Tech Stack: NextJs (version below 13), ChakraUI (Utilizing predefined components, mainly Flex) The concept is as follows: After testing different screen sizes and determining when UI eleme ...

How can I access other properties of the createMuiTheme function within the theme.ts file in Material UI?

When including a theme in the filename.style.ts file like this: import theme from 'common/theme'; I can access various properties, such as: theme.breakpoints.down('md') I am attempting to reference the same property within the theme ...