繁体   English   中英

尝试使用 React Native 对 Flask 后端发出 Axios HTTP 请求

[英]Trying to make Axios HTTP request with React Native to Flask backend

I am trying to make a HTTP request via Axios inside react native to my backend flask app login endpoint, however when I run Expo, type the username and hit 'Login', my Online Status still remains 'Offline'. 有人可以帮我解决这个问题吗?

这是我的 flask 代码:

from flask import Flask, request, abort, jsonify

app = Flask(__name__)

users = []

@app.route("/login", methods=["POST"])
def login():
username = request.json.get('username', None)
if username is None or username in users:
    abort(401)
else:
    users.append(username)
    return jsonify({
    'status': 'OK',
    'message': 'Successfully Logged in'
    })


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')
#app.run(debug=True)
#app.run(debug=True, host='http://127.0.0.1:5000') 
#app.run(debug=True, host='http://146.203.130.213:5000')

这是我的 react-native 代码:

import React from 'react';
import { StyleSheet, Text, View, TextInput, Button, FlatList } from 
'react-native';
import axios from 'axios';

const serverUrl = '{my IP address}:5000';
//const serverUrl = 'http://127.0.0.1:5000';
const http = axios.create({
baseURL: serverUrl,
}); 

export default class App extends React.Component {
constructor(props) {
 super(props);
  this.state = {
   input: '',
   messages: [],
  };
}

onLogin() {
 const { isLoggedIn, username } = this.state;
  if (!isLoggedIn) {
   http.post('/login', {username})
    .then(() => this.setState({isLoggedIn: true}))
    .catch((err) => console.log(err))
  }  
 }

render() {
 const { messages, isLoggedIn } = this.state;
  return (
  <View style={styles.container}>
   <View>
   <Text>Login</Text>
   <TextInput
   onChangeText={(val) => this.setState({username: val})}
   />
  <Button title='Login' onPress={() => this.onLogin()} />
  <Text> Online Status: {isLoggedIn ? 'Online' : 'OffLine'}</Text>
 </View>
</View>
);
}
}

const styles = StyleSheet.create({
  container: {
  flex: 1,
  backgroundColor: '#fff',
  alignItems: 'center',
  justifyContent: 'center',
  },
});

任何帮助将不胜感激。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM