【问题标题】:Network Error with Axios on server with express.js带有express.js的服务器上的Axios网络错误
【发布时间】:2021-10-10 21:06:12
【问题描述】:

我使用 express.js 在 localhost:3000 上运行了一个 API,结果如下:

0   
_id:    "610bcbd9c0ce881847bfd5b6"
__v:    0
1   
_id:    "610bcc43c0ce881847bfd5b8"
name:   "haaa"
title:  "data"
title2: "data2"
__v:    0
2   
_id:    "610bcc5ec0ce881847bfd5ba"
name:   "haaa"
title:  "data"
title2: "data7"
__v 0
3   
_id:    "610bcd00303b9a1b041d9d6a"
name:   "haaa"
title:  "data"
title2: "data7"
__v:    0

当我运行 axios.get 时,我收到一个错误。

app.js 上的代码:

const [data, setData] = useState();
    useEffect(() => { 
        async function fetchmyapi() {
            try {
            let response = await axios.get('http://localhost:3000/')
            setData(response)
            console.log(data)

            }
            catch(error) {
                console.log(error)
            }
        }
        fetchmyapi()
        }, [])

这是 console.log 中的错误:

Network Error
at node_modules/axios/lib/core/createError.js:1:0 in <global>
at node_modules/axios/lib/adapters/xhr.js:74:24 in handleAbort
at node_modules/react-native/Libraries/Network/XMLHttpRequest.js:600:10 in setReadyState
at node_modules/react-native/Libraries/Network/XMLHttpRequest.js:395:6 in __didCompleteResponse
at node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:189:10 in emit
at [native code]:null in callFunctionReturnFlushedQueue

有什么问题,我可以使用其他东西而不是 Axios 吗?

【问题讨论】:

    标签: react-native express axios localhost


    【解决方案1】:

    您收到错误是因为_id 当你从后端向前端发送数据时,你需要将_id从ObjectID转换为字符串。
    如果你这样做,就没有错误。

    【讨论】:

    • 感谢您的回答。你能给我更多的细节吗?我该怎么办?
    • https://stackoverflow.com/questions/13104690/nodejs-mongodb-object-id-to-string/34445430 请检查一下。
    • 你用什么模块连接mongodb? mongoose' or mongodb`?
    • 我用猫鼬,
    • ` app.get('/',(req,res) =>{ Ads.find({}) .then(data =>{ console.log(data) _id.toString() res.send(data) }).catch(err => { console.log(err) }) }) `
    【解决方案2】:

    所以我终于可以弄清楚了:

    1- 不要使用localhost:3000 作为Url,找到您的网络IP 并使用它来代替192.168.1.102

    2- Axios 制造问题。改用fetch

    useEffect(() => { 
            async function fetchmyapi() {
                try {
                let response = await fetch('http://yourIP:3000/')
    .then((response) => response.json())
                setData(response)
                }
                catch(e) {
                    console.log(e)
                }
            }
            fetchmyapi()
            }, [])
    

    【讨论】:

      猜你喜欢
      • 2021-02-15
      • 2023-03-27
      • 2014-09-18
      • 1970-01-01
      • 2022-01-02
      • 2020-04-14
      • 1970-01-01
      • 1970-01-01
      • 2021-08-05
      相关资源
      最近更新 更多