如何用React Native作为前端对接CodeIgniter 3后端?求登录示例代码
React Native 与 CodeIgniter 3 登录对接示例
CodeIgniter 3 后端登录接口
1. 登录控制器 (application/controllers/Auth.php)
处理登录请求、参数验证、用户校验并返回JSON格式响应:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Auth extends CI_Controller { public function __construct() { parent::__construct(); // 跨域配置(生产环境请限制具体域名) header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Methods: POST, OPTIONS"); header("Access-Control-Allow-Headers: Content-Type"); // 处理OPTIONS预检请求 if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit(); $this->load->model('Auth_model'); $this->load->library('form_validation'); } public function login() { // 参数验证规则 $this->form_validation->set_rules('email', '邮箱', 'required|valid_email'); $this->form_validation->set_rules('password', '密码', 'required'); if ($this->form_validation->run() === FALSE) { echo json_encode([ 'status' => false, 'message' => validation_errors() ]); return; } $email = $this->input->post('email'); $password = $this->input->post('password'); // 查询用户 $user = $this->Auth_model->get_user_by_email($email); if (!$user) { echo json_encode([ 'status' => false, 'message' => '用户不存在' ]); return; } // 验证哈希密码 if (!password_verify($password, $user['password'])) { echo json_encode([ 'status' => false, 'message' => '密码错误' ]); return; } // 返回成功数据 echo json_encode([ 'status' => true, 'message' => '登录成功', 'user' => [ 'id' => $user['id'], 'name' => $user['name'], 'email' => $user['email'] ] ]); } }
2. 用户模型 (application/models/Auth_model.php)
负责数据库查询逻辑:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Auth_model extends CI_Model { public function get_user_by_email($email) { $this->db->where('email', $email); return $this->db->get('users')->row_array(); } }
注意:确保数据库
users表包含id、name、password字段,且密码通过password_hash()存储哈希值。
React Native 前端登录实现
创建LoginScreen组件,通过fetch发送登录请求:
import React, { useState } from 'react'; import { View, TextInput, Button, Text, StyleSheet, Alert } from 'react-native'; const LoginScreen = () => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [isLoading, setIsLoading] = useState(false); const handleLogin = async () => { if (!email || !password) { Alert.alert('提示', '请填写邮箱和密码'); return; } setIsLoading(true); try { const response = await fetch('http://你的CI3服务器IP/index.php/Auth/login', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: `email=${encodeURIComponent(email)}&password=${encodeURIComponent(password)}` }); const result = await response.json(); if (result.status) { Alert.alert('成功', result.message); // 登录成功后可将用户信息存入AsyncStorage console.log('用户信息:', result.user); } else { Alert.alert('错误', result.message); } } catch (error) { Alert.alert('错误', '网络请求失败,请检查接口地址或网络'); console.error(error); } finally { setIsLoading(false); } }; return ( <View style={styles.container}> <TextInput style={styles.input} placeholder="邮箱" keyboardType="email-address" value={email} onChangeText={setEmail} autoCapitalize="none" /> <TextInput style={styles.input} placeholder="密码" secureTextEntry value={password} onChangeText={setPassword} /> <Button title={isLoading ? '登录中...' : '登录'} onPress={handleLogin} disabled={isLoading} /> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', padding: 20, backgroundColor: '#fff', }, input: { height: 40, borderColor: '#ccc', borderWidth: 1, marginBottom: 15, paddingHorizontal: 10, borderRadius: 5, }, }); export default LoginScreen;
关键注意事项
- 跨域安全:生产环境需将
Access-Control-Allow-Origin设置为React Native应用的具体域名/IP,禁止使用*。 - 数据传输:必须使用HTTPS协议,避免明文数据泄露。
- 接口地址:本地测试时用服务器IP而非
localhost,确保设备与服务器在同一网络。 - 参数格式:若改用JSON格式传递参数,后端需通过
$this->input->raw_input_stream解析请求体。
内容的提问来源于stack exchange,提问作者5r33
相关产品推荐
相关产品推荐

