我正在尝试使用express和node.js将来自server.js的数据发送到我在React Native中的客户端,双方都可以单独工作,但彼此之间没有通信。我对后端开发还很陌生,所以我开始了解它的功能以及如何实现所需的行为。任何人都可以帮忙吗?
server.js
const express = require('express')
const app = express()
const port = process.env.PORT || 5000;
app.get('/',(req,res) => {
res.send({ express: 'YOUR EXPRESS BACKEND IS CONNECTED TO REact' })
}
)
app.listen(port,() => console.log(`Example app listening on port ${port}!`))
app.js
import React,{ Component } from "react";
import {Modal,StyleSheet,View,StatusBar,Text,activityIndicator,flatList} from 'react-native'
export default class FetchExample extends React.Component {
constructor(props){
super(props);
this.state = {
data: ''
};
}
componentDidmount() {
// Call our fetch function below once the component mounts
this.callBackendAPI()
.then(res => this.setState({ data: res.express }))
.catch(err => console.log(err));
}
// Fetches our GET route from the Express server. (Note the route we are fetching matches the GET route from server.js
callBackendAPI = async () => {
const response = await fetch('/');
const body = await response.json();
if (response.status !== 200) {
throw Error(body.message)
}
return body;
};
render(){
return(
<View style={{flex: 1,paddingTop:20}}>
<Text>{this.state.data}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,justifyContent: 'center',},});
package.Json
{
"name": "mapp","version": "0.0.1","private": true,"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start","test": "jest"
},"dependencies": {
"@expo/vector-icons": "^10.0.2","babel-plugin-mobx-deep-action": "^1.6.1","express": "^4.17.1","jetifier": "^1.6.3","jsc-android": "241213.x.x","mobx": "^5.11.0","mobx-react": "^6.1.1","native-base": "^2.13.8","react": "16.8.3","react-native": "^0.59.10","react-native-background-fetch": "^2.6.0","react-native-background-geolocation": "^3.0.7","react-native-css-gradient": "^0.3.1","react-native-drop-down-item": "^1.0.5","react-native-dropdown-menu": "^2.0.0","react-native-elements": "^1.2.6","react-native-gesture-handler": "^1.3.0","react-native-input-scroll-view": "^1.9.3","react-native-ionicons": "^4.5.6","react-native-linear-gradient": "react-native-community/react-native-linear-gradient","react-native-maps": "^0.24.2","react-native-responsive-screen": "^1.2.2","react-native-svg": "^9.5.2","react-native-svg-transformer": "^0.13.0","react-native-vector-icons": "^6.5.0","react-native-vertical-tab-view": "^0.1.3","react-navigation": "^3.11.0","react-redux": "^7.1.0","redux": "^4.0.1"
},"devDependencies": {
"@babel/core": "7.4.5","@babel/plugin-proposal-decorators": "^7.4.4","@babel/runtime": "7.4.5","babel-jest": "24.8.0","babel-preset-react-native": "4.0.0","jest": "24.8.0","metro-react-native-babel-preset": "0.54.1","react-test-renderer": "16.8.3","redux-devtools": "^3.5.0"
},"jest": {
"preset": "react-native"
},"proxy": "http://localhost:5000/"