Home > Back-end >  Node server gives me undefined when I send data
Node server gives me undefined when I send data

Time:06-19

I'm trying to send data to the server but when I log it gives me undefined even tho I can log it on the client. I think I'm missing something.

Thanks in Advance!

Client

const handleSubmit = async (e) => {
    e.preventDefault()
    try{
      const response = await axios.post('http://localhost:8000/send', {formData})
      console.log(response)
    } catch(error){
      console.log(error)
    }
  }

Server

app.post('/send', async (req, res) => {
    console.log(req.body)
    res.send("ok")
})

CodePudding user response:

I think you might need to set a header on the request

try adding config object as a 3rd argument

const config = {
        headers: {'Content-Type': 'application/json'}
    }


const handleSubmit = async (e) => {
    e.preventDefault()
    try{
      const response = await axios.post('http://localhost:8000/send', 
      {formData}, config)
      console.log(response)
    } catch(error){
      console.log(error)
    }
  }

CodePudding user response:

remove the object property shorthand, use just formData:

 const response = await axios.post('http://localhost:8000/send', formData)

CodePudding user response:

//client
const handleSubmit = async (e) => {
    e.preventDefault()
    const config = {
      "headers":{
        "Content-Type":"application/json"
      }
    }
    const body = JSON.stringify({
      formData
    })
    try{
      const response = await axios.post('http://localhost:8000/send', body, config)
      console.log(response)
    } catch(error){
      console.log(error)
    }
  }
  
  // server 
  const express = require("express");
  const app = express();
  app.use(express.json()); // this is necessary

  app.post('/send', async (req, res) => {
    console.log(req.body)
    res.send("ok")
})

  
  
  

Hope it helps!

  • Related