简体   繁体   中英

How to get data from api using axios

Postman gets the data correctly but axios get the wrong data, it receives the "Not found" but there is a record in DB.

react hook:

import axios from "axios";
import {useEffect, useState} from "react";

export default function useRoom(roomName) {
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)
  const [room, setRoom] = useState({})
  useEffect(() => {
    setLoading(true)
    axios({
      method: "POST",
      body: {
        "roomName": "test1"
      },
      withCredentials: true,
      url: "http://localhost:4444/room",
    }).then(res => {
      setRoom(res.data)
      console.log(res)
      setLoading(false)
    }).catch(e => {
      setError(e.toString())
      setLoading(true)
    })
  }, [roomName])

  return {
    error,
    room,
    loading
  }
}

NODE JS:

app.post('/room', (req, res) => {
  Room.findOne({roomName: req.body.roomName}, async (err, doc) => {
    if (err) throw err;
    if (!doc) res.send("No Room Found");
    else {
      res.send(doc);
    }
  })
})

Postman receives the data but the axios doesn't

邮递员工作正常

I have the data in my db蒙戈地图集

What I get in the browser console:

在此处输入图片说明

How I use my hook: 在此处输入图片说明

If someone knows how to solve this issue please let me know

I'm not sure but maybe you should use 'data' instead of 'body' :

axios({
  method: "POST",
  data: { // <--- HERE 
    "roomName": "test1"
  },
  withCredentials: true,
  url: "http://localhost:4444/room",
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM