Home > Back-end >  Reactjs Axios PUT empty data
Reactjs Axios PUT empty data

Time:11-29

So i'm trying to make an add order page form which should submit data into the user's orders[] collection (mongoDB).

The backend works just fine and does exactly what it is meant to do, but the frontend form just submits empty data although the request status is 200.

This is the form

export default function OrderForm() {
    const [email, setEmail] = useState('')
    const [ticker, setTicker] = useState('')
    const [amount, setAmount] = useState('')
    const [price, setPrice] = useState('')
    const [date, setDate] = useState('')
    const [comments, setComments] = useState('')

    const handleSubmit = async(value) =>{
        value.preventDefault()

        const orders = {
            ticker: ticker,
            amount: amount,
            price: price,
            date: date,
            comments: comments
        }

        console.log(orders)

        try{
            axios.put(`http://localhost:8081/api/auth/order/:email?=${email}`, {
                data: orders
            })
            .then((res) => {
                if(res){
                    console.log(res)
                    console.log(`Order saved to ${email}'s account`)

                }
            }).catch(e =>{
                console.log(e)
            })

        }catch(error){
            console.error(error)
        }
    }

The form outputs this: Console log of form

This is the backend code which works when i test it with Postman:

exports.addOrder = async (req, res) => {

  const {email} = req.params

  const {
    ticker,
    amount,
    price,
    date,
    comments

  } = req.body;

  try{
    const user = await User.findOneAndUpdate({
      email: email
    }, {
      $push: {
        orders: {
          ticker: ticker,
          amount: amount,
          price: price,
          date: date,
          comments: comments

        }
      },
    })

    if (!user) {
      console.log('Sorry that user does not exist')
    }

    res.status(200).send(user).json({
      message: `Order: ${orders} \n has been added to ${user}`
    });

  }catch(error) {
    res.status(400).json({
      error: error.message
    })
  }
}

CodePudding user response:

You're using url as http://localhost:8081/api/auth/order/:email?=${email}, You have to use http://localhost:8081/api/auth/order/${email}

For more information: (https://v5.reactrouter.com/web/example/query-parameters)

  • Related