You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native(Expo)与Spring Boot的CORS跨域请求问题排查

问题

我使用React Native Expo与Spring Boot开发跨平台应用,已在Spring Boot中配置addCorsMappings,但React Native应用无法发送任何HTTP请求(fetch)。常规HTML页面的JavaScript可正常从服务器获取数据,但React Native在iOS和Android平台均无法实现。

尝试过@CrossOrigin注解仍无效,但React Native能正常请求在线免费测试API。请问问题出在哪?如何让React Native成功向服务器发送请求?

Spring Boot CORS配置代码

package com.example.apiTest.config;

import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

public class webConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry){
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET","POST","PUT","DELETE","HEAD","PATCH","OPTIONS")
                .allowCredentials(true);
    }
}

可正常运行的HTML测试代码

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>HTTP GET Example</title>
</head>
<body>
  <button type="button" onclick="sendRequest()">Send Request</button>

  <script>
    function sendRequest() {
      fetch('http://localhost:8090/member/test')
        .then(response => response.json())
        .then(data => {
          console.log('Success:', data);
        })
        .catch((error) => {
          console.error('Error:', error);
        });
    }
  </script>
</body>
</html>

React Native相关代码

请求函数

const testFunc = async () => {
  fetch('http://localhost:8090/member/test')
  .then(response => response.json())
  .then(data => {
    console.log('Success:', data);
  })
  .catch((error) => {
    console.error('Error:', error);
  });
};

页面组件

const LogInPage = () => {
  const [id, onChangeid] = React.useState();
  const [passWord, onChangeText2] = React.useState();
  const[disabled, setDisabled]=React.useState(false);

  return (
    <SafeAreaView>        
      <TouchableOpacity
        onPress={testFunc} 
        disabled={disabled}
        style={styles.button}
        >
          <Text style={{color : 'white'}}>로그인</Text>
    </TouchableOpacity>
    </SafeAreaView>
  );
};

样式与入口

const styles = StyleSheet.create({
  input: {
    height: 40,
    margin: 15,
    borderWidth: 1,
    padding: 10,
    top : 10,
  },
  container:{
    flex:1,
    justifyContent : 'center',
    paddingHorizontail : 10,
  },
  button:{
    alignItems : 'center',
    backgroundColor : 'gray',
    padding : 10,
  },
  text:{
    color : 'white',
    fontWeight : 'bold',
  },
});

const Tab = createBottomTabNavigator();

export default function App() {
  return (
    LogInPage()
  );
};

解决方案

1. 首要问题:localhost指向错误

React Native运行在模拟器或真机上时,localhost指向的是设备自身,而非你的开发电脑。这就是浏览器里的HTML能访问,但React Native不行的核心原因。

2. 针对不同设备的修正方案

  • iOS模拟器:可以直接使用http://localhost:8090或http://127.0.0.1:8090,iOS模拟器默认与开发电脑共享网络栈。
  • Android模拟器:替换为http://10.0.2.2:8090(Android模拟器将此地址映射到开发电脑的localhost),或者使用电脑的局域网IP。
  • 真机测试:确保手机与电脑在同一局域网,使用电脑的局域网IP(如http://192.168.x.x:8090),同时在Spring Boot的application.properties中添加server.address=0.0.0.0,允许服务被局域网访问。

3. 关键配置检查:Spring Boot CORS配置未生效

你的webConfig类缺少@Configuration注解,Spring不会自动扫描并应用这个配置。修改后的配置类如下:

package com.example.apiTest.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration // 必须添加此注解
public class webConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry){
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET","POST","PUT","DELETE","HEAD","PATCH","OPTIONS")
                .allowCredentials(true);
    }
}

4. 额外验证步骤

  • 先在设备的浏览器中访问API地址,确认能正常返回JSON数据,排除网络连通性问题。
  • 检查电脑防火墙是否开放了8090端口,允许模拟器/真机访问。

内容的提问来源于stack exchange,提问作者DSJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 16:40:32