reactjs React Native不会连接到API,但React和浏览器可以

r8xiu3jd  于 11个月前  发布在  React
关注(0)|答案(1)|浏览(162)

我正在使用React Native Expo与Android,React和Express作为API。
当我访问API的地址时,我会收到一条消息。当我从React中获取它时,我会收到一条消息。当我尝试从React Native中获取时,我在控制台中得到“Error fetching data:[TypeError:Network request failed]”,而JS调试器中什么都没有。
我已经尝试了多个端口的所有来源和axios。我已经改变了特定端口的cors,重新启动一切多次,检查权限。
这里是我做的测试应用程序-我每次都得到相同的结果。谢谢!
表达

const express = require('express');
const cors = require('cors'); // Import the cors middleware
const app = express();
const port = 4321;

// Use the cors middleware
app.use(cors());

app.get('/', (req, res) => {
  res.send({message: 'Hello'});
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

字符串
React Native

import React, { useEffect } from 'react';

const App = () => {
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch('http://localhost:4321');
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }

        const data = await response.json();
        console.log('Data from the server:', data);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, []);

  return (
    <></>
  );
};

export default App;


React(与RN相同)

import React, { useEffect } from 'react';

const App = () => {
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch('http://localhost:4321');
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }

        const data = await response.json();
        console.log('Data from the server:', data);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();
  }, []);

  return (
    <></>
  );
};

export default App;

tct7dpnv

tct7dpnv1#

在React和React Native应用中,将'http://localhost:4321'替换为本地IP地址。

// React Native
const response = await fetch('http://your-local-ip:4321');

// React
const response = await fetch('http://your-local-ip:4321');

字符串

查找本地IP地址:
Windows系统:打开命令行,运行ipconfig,在当前网络连接下查找IPv4地址
在macOS/Linux上:打开终端,运行ifconfig或ip a,在活动网络连接下查找
“inet”**地址。

相关问题