从React Native前端到本地spring后端服务的Axios API请求不工作



我开发了一个React Native移动应用程序,后端我想使用Java Spring。现在我有一个独立的后端服务器在8080端口本地运行,我的react native应用程序是通过Expo Go应用程序运行的。

对于这个问题,我建立了一个非常简单的例子。在前端应用程序中,我想做一个GET请求从后端检索字符串,我使用axios发送API请求。问题是,每当我向http://localhost:8080/发送get请求时,我都会得到Network Error错误
// dont bother func name
const loginUser = () => {
axios.get("http://localhost:8080/").then(value => {
console.log(value)
}).catch(err => {
console.log("REQUEST FAILED")
console.log(err)
})}

这是用户按下按钮时axios请求被发送的处理程序,预期输出:"Hello World">

输出:

REQUEST FAILED
Network Error
at node_modulesaxioslibcorecreateError.js:17:22 in createError
at node_modulesaxioslibadaptersxhr.js:120:6 in handleError
at node_modulesevent-target-shimdistevent-target-shim.js:818:20 in EventTarget.prototype.dispatchEvent
at node_modulesreact-nativeLibrariesNetworkXMLHttpRequest.js:600:10 in setReadyState
at node_modulesreact-nativeLibrariesNetworkXMLHttpRequest.js:395:6 in __didCompleteResponse
at node_modulesreact-nativeLibrariesvendoremitterEventEmitter.js:189:10 in emit
at node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:416:4 in __callFunction
at node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:109:6 in __guard$argument_0
at node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:364:10 in __guard
at node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:108:4 in callFunctionReturnFlushedQueue

@RestController
//@CrossOrigin(origins = "*")
public class TestController {

@GetMapping("/")
public String hello(){
return "Hello World";
}
}

Simple Spring REST Controller

@SpringBootApplication
public class JpaApplication {
public static void main(String[] args) {
SpringApplication.run(JpaApplication.class, args);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("GET","POST","PUT","DELETE").allowedHeaders("*").allowedOrigins("*");
}
};
}
}

CORS配置只允许所有

我试过把注释@CrossOrigin(origins = "*")上面的控制器,但它没有帮助(从:React和Axios: Axios可以't访问Java/SpringBoot REST后端服务,因为CORS策略)。我已经允许从CORS配置中的所有位置进行所有访问,但我得到相同的输出。这个例子非常简单。我只是想得到一个简单的字符串,解决方案可能也很简单,但经过这么多次尝试,我不能想出一个解决方案。如果我访问浏览器上的URL,我得到了预期的值,但通过axios请求,它似乎不起作用。

经过更多的搜索,我发现不可能在Android模拟器上直接向localhost发送请求,在IOS上没有问题。所以问题毕竟是在React Native方面。

所以修复相对容易,也在stackoverflow上发现,以下线程帮助很大:React Native Android Fetch连接到本地API失败。

我安装了ngrok,它生成了一个URL,我可以用它来临时测试我的后端,直到我托管它。

最新更新