gpt4 book ai didi

android - express 端口 3000,react native 端口 8081,如何发出 get 请求

转载 作者:行者123 更新时间:2023-11-29 15:40:05 27 4
gpt4 key购买 nike

我正在使用 React Native 作为我想要部署到 iOS 和 Android 的头像生成器。我正在为我的服务器使用 Express,它使用 localhost:3000,react native 使用 localhost:8081。

import axios from 'axios';
import React, { Component } from 'react';
import { AppRegistry, Text } from 'react-native';
import { Container, List, ListItem, Header, Title, Content, Thumbnail } from 'native-base';
import { Action } from 'react-native-router-flux';

export default class Class extends Component {
componentWillMount(){
axios.get('https://localhost:3000')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}

render() {
return (
<Container>
<Header><Title>Choose Race</Title></Header>
<Content> contents here <Content>);}}

我在 React Native 调试器中收到以下错误

Error: Network Error
at createError (createError.js:15)
at XMLHttpRequest.handleError (xhr.js:87)
at XMLHttpRequest.dispatchEvent (event-target.js:172)
at XMLHttpRequest.setReadyState (XMLHttpRequest.js:542)
at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:378)
at XMLHttpRequest.js:482
at RCTDeviceEventEmitter.emit (EventEmitter.js:181)
at MessageQueue.__callFunction (MessageQueue.js:236)
at MessageQueue.js:108
at guard (MessageQueue.js:46)

最佳答案

在android模拟器中,localhost指的是android系统。您使用 10.0.2.2 来引用它。例如。 http://10.0.2.2:3000 ( How to connect to my http://localhost web server from Android Emulator in Eclipse )

虽然在 iOS 模拟器中,localhost 确实指的是主机:How do I access the host machine itself from the iPhone simulator

在本地测试时,您可能必须执行一些特定于平台的逻辑,例如:

import { Platform } from 'react-native';

const host = Platform.select({
ios: 'localhost',
android: '10.0.2.2',
});

// ...
axios.get(`http://${host}:3000/`)
// ...

关于android - express 端口 3000,react native 端口 8081,如何发出 get 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42125397/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com