REACT+PHP课程项目血泪史
在React和PHP结合的课程项目中,我们可以假设有一个简单的登录表单,用户可以在其中输入用户名和密码,然后通过REST API发送到后端进行验证。以下是实现这个功能的代码示例:
React (JavaScript) 前端组件:
import React, { useState } from 'react';
import axios from 'axios';
const LoginForm = () => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = async (event) => {
event.preventDefault();
try {
const response = await axios.post('http://your-php-backend.com/api/login', {
username,
password,
});
// 处理登录成功的逻辑,例如保存token
console.log(response.data);
} catch (error) {
// 处理登录失败的逻辑
console.error('Login failed', error);
}
};
return (
<form onSubmit={handleSubmit}>
<label>
Username:
<input type="text" value={username} onChange={(e) => setUsername(e.target.value)} />
</label>
<label>
Password:
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
</label>
<button type="submit">Login</button>
</form>
);
};
export default LoginForm;
PHP (后端) 代码示例:
<?php
// api/login 路由处理登录请求
$method = $_SERVER['REQUEST_METHOD'];
if ($method === 'POST') {
$input = file_get_contents('php://input');
$data = json_decode($input, true);
// 假设用户数据存储在数据库中,这里简化为硬编码用户检查
$users = [
['username' => 'user1', 'password' => 'pass1', 'token' => 'token1'],
// ... 其他用户
];
foreach ($users as $user) {
if ($user['username'] === $data['username'] && $user['password'] === $data['password']) {
// 登录成功,返回token
http_response_code(200);
header('Content-Type: application/json');
echo json_encode(['token' => $user['token']]);
exit;
}
}
// 登录失败,返回错误
http_response_code(401);
header('Content-Type: application/json');
echo json_encode(['error' => 'Invalid username or password']);
exit;
}
http_response_code(405);
header('Content-Type: application/json');
echo json_encode(['error' => 'Method not allowed']);
exit;
?>
评论已关闭