Issues with Axios POST requests

I've been facing an issue with using Axios to send a POST request to my Node.js server. Any suggestions on how I can troubleshoot this problem?

Here is a snippet of the code in question:

server.js:

app.post('/registration', (req, res) => {
  console.log(req.body);
});

Below is a section of my component class:

export default class Registration extends Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.state = {}
  }
  handleSubmit(e) {
    e.preventDefault;
    axios.post('/registration', {name: document.getElementById('name') }).then(res => {
      console.log(res);
    })
    }
  render() {
    return (<form className="registrationForm">
      <input type="text" name="name" id="name" required="required" placeholder="name"/>
      <br/>
      {/*<input type="text" name="email" required="required" placeholder="email"/>
      <br/>
      <input type="number" name="phoneNumber" required="required" placeholder="phoneNo"/>
      <br/>
      <input type="password" name="password" required="required" placeholder="pass"/>
      <br/> */}
      <button className="registerButton" onClick={this.handleSubmit}>register</button>
    </form>)
  };
}

https://i.stack.imgur.com/VR8VE.png

Answer №1

Your code is presenting several issues that need attention

  • The method preventDefault needs to be called in order to function properly
  • Sending a DOM element to the server may not be the intended action
  • To handle network failure, it is recommended to use catch

A revised version of handleSubmit should resemble the following:

handleSubmit (e) {
    e.preventDefault(); // Important
    const data = {name: document.getElementById('name').value /* Important */ };

    axios.post('/registration', data).then(res => {
      console.log(res);
    }).catch(console.error) // This will help identify any potential issues
  }

In general, it is not advisable to use DOM lookup methods within your React components. It is better practice to maintain a ref to the input element.

<input ... ref={input => this.name = input}/>
const data = {name: this.name.value };

Answer №2

After encountering an issue in my server side application, I discovered that the problem stemmed from a single line that was missing.

To resolve this issue, make sure to include the following lines after requiring the body-parser in your file:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

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

What could be causing a template value in my AngularJS/Ionic Framework code to not be replaced properly?

Recently, I've been exploring the world of Ionic Framework with Angular by my side. However, I've hit a bit of a roadblock. My goal is to set up tabs at the bottom of my application using a model definition. Here's what I've tried so ...

My API is feeding data to the Material UI CardMedia image

Has anyone encountered a similar error while using the CardMedia API provided by Material-UI? I am currently utilizing the Card & CardMedia components from material-ui to display data fetched from an api. However, I am facing difficulty in displaying ...

Having trouble updating a specific document in my MongoDB collection

I am facing an issue with my function that reads data from the database. I am trying to change the value of the "hasVoted" field in my Voters model from false to true, but it is not reflecting in the database. Even after setting data.hasVoted = true and c ...

The value returned is undefined when using getStaticProps

Recently, while working on my project with Next.js, I encountered an issue where I was trying to access data but kept getting undefined. Below is the code snippet that I was working with: function Home({books}) { console.log(books) return <div>Home ...

Guide on retrieving the state within a function

this.state = { color: { B: '#FFB1C2', // RED C: '#A7EBEB', // GREEN D: '#99BFFF', // BLUE E: '#F9C499', // ORANGE F: '#B2A9A7&apo ...

Step-by-step guide on redirecting to a different page in NextJS if a dynamic route cannot be found

I need assistance with redirecting users when they access a dynamic route that does not exist. The dynamic route points to a field within a statically defined array of fields. Here is the code snippet for the page: import { fields } from "@/data/fiel ...

The class function in the exported typescript logs that "this" is not defined

I am currently facing an issue with my TypeScript class where I am setting class values in a constructor and referencing them using "this" in a class method. While the .ts file compiles without any warnings, when I import the compiled .js file into another ...

Challenge with using the React useEffect hook

Incorporating the React useEffect hook into my code has been a bit challenging. Here is how I am attempting to use it: function App() { React.useEffect(() => { console.log('effect working') }, []) return ( <div className=" ...

Utilizing event listeners with image elements in React for interactive typing experience

When I attempt to type the event as React.ChangeEvent<HTMLImageElement> in order to make the e.target.src work, I encounter the following error messages in the imageFound and ImageNotFound functions: Type '(evt: React.ChangeEvent) => void&a ...

Step-by-step guide on installing solely 'devDependencies' with npm

Looking to specifically install only the "devDependencies" from my package.json file, I've attempted various commands with no success. Each command ends up installing both production and development dependencies, which is not what I want. npm install ...

Changing the text field label color with React and Material-UI when it's in focus

https://i.stack.imgur.com/xpIAs.png My goal is to make the text "First Name" appear in red color. To achieve this, I used the following code snippet: <TextField id="outlined-basic" label="First name" variant="outlined" ...

The Slack-App-Watson feature seems to have trouble retaining the intent from the previous message it received

Currently, I am developing a Slack bot with the ability to retrieve weather information for a specified location. In the Watson conversation chat interface, Watson is performing well: me: Weather please Watson (detected #weather_asked): Where wou ...

Sending a `refresh` to a Context

I'm struggling to pass a refetch function from a useQuery() hook into a context in order to call it within the context. I've been facing issues with type mismatches, and sometimes the app crashes with an error saying that refetch() is not a funct ...

Learn how to create a button that will only submit a value when clicked using Node.js and EJS

Currently in my ejs file, I have a button that sends a value to app.js instantly when the program runs. However, I want it to only submit the value when clicked by the user. <% notesArray.forEach((note,i) =>{ %> <div class="note"> ...

Struggling to get the most recent version of NPM to function properly

I'm currently attempting to upgrade my npm to the latest version as I am currently using 1.4.28. I have used the following command: npm update -g npm Upon executing this command, I received the following output: <a href="/cdn-cgi/l/email-protect ...

Errors related to TypeScript syntax have been detected within the node_modules/discord.js/typings/index.d.ts file for Discord.JS

I keep encountering typescript syntax errors after pulling from my git repository, updating all npm modules on the server, and running the start script. The errors persist even when using npm run dev or npx tsc. I've attempted the following troublesh ...

Receiving a blank array upon calling res.json() in Node.js script

I'm facing an issue with my code snippet that displays all posts, including the username and display picture of each user. Everything seems to be working fine as the log output is perfect. However, I'm struggling to return this data as a JSON obj ...

accessing data fields using connect-busboy and node/express

I am a beginner when it comes to node.js. Despite researching on Google for the past three days, I still can't figure out what's wrong. I have tried some solutions suggested here, but it seems like I'm missing something. I have recently inst ...

Is there a way to download and store the PDF file created using html2pdf in Node.js on my local machine?

I have successfully generated a PDF using html2pdf, but now I want to either send it to my server in Node.js or save it directly onto the server. Currently, the PDF is downloaded at the client's specified path, but I also need a copy saved on my serve ...

Encountered a 'SyntaxError: await is only valid in async function' error while trying to utilize the top-level await feature in Node v14.14.0

I'm excited to use the new top-level await feature that was introduced in Node version 14.8. For more information, you can check out this link and here. I did a thorough search but couldn't find any questions related to issues with the new featur ...