我可以为你提供一个详细的App代码网站示例,这个示例将包括一个简单的待办事项列表(To-Do List)应用的前端和后端代码。
技术栈
前端: HTML, CSS, JavaScript (使用React)
后端: Node.js, Express
数据库: MongoDB (使用Mongoose)
项目结构
todo-app/ ├── client/ │ ├── public/ │ ├── src/ │ │ ├── components/ │ │ ├── App.js │ │ ├── index.js │ │ └── index.html │ ├── package.json ├── server/ │ ├── models/ │ ├── routes/ │ ├── app.js │ ├── package.json └── .gitignore
前端代码 (client/src/index.js)
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './styles.css'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root') );
前端代码 (client/src/App.js)
import React, { useState, useEffect } from 'react'; import axios from 'axios'; import './App.css'; function App() { const [tasks, setTasks] = useState([]); const [newTask, setNewTask] = useState(''); useEffect(() => { axios.get('/api/tasks') .then(response => setTasks(response.data)) .catch(error => console.error('Error fetching tasks:', error)); }, []); const addTask = () => { const task = { id: Date.now(), text: newTask, completed: false }; axios.post('/api/tasks', task) .then(response => setTasks([...tasks, response.data])) .catch(error => console.error('Error adding task:', error)); setNewTask(''); }; return ( <div className="App"> <h1>To-Do List</h1> <input type="text" value={newTask} onChange={e => setNewTask(e.target.value)} /> <button onClick={addTask}>Add Task</button> <ul> {tasks.map(task => ( <li key={task.id}> <span>{task.text}</span> <button>{task.completed ? 'Undo' : 'Complete'}</button> </li> ))} </ul> </div> ); } export default App;
前端代码 (client/src/App.css)
body { font-family: Arial, sans-serif; } .App { max-width: 600px; margin: 0 auto; padding: 20px; } input { width: calc(100% 80px); padding: 10px; margin-right: 10px; } button { padding: 10px; }
后端代码 (server/models/task.js)
const mongoose = require('mongoose'); const taskSchema = new mongoose.Schema({ text: { type: String, required: true }, completed: { type: Boolean, default: false }, }); module.exports = mongoose.model('Task', taskSchema);
后端代码 (server/routes/tasks.js)
const express = require('express'); const router = express.Router(); const Task = require('../models/task'); router.get('/', async (req, res) => { try { const tasks = await Task.find(); res.json(tasks); } catch (error) { res.status(500).json({ message: 'Error fetching tasks' }); } }); router.post('/', async (req, res) => { const task = new Task(req.body); try { const newTask = await task.save(); res.status(201).json(newTask); } catch (error) { res.status(400).json({ message: 'Error adding task' }); } }); module.exports = router;
后端代码 (server/app.js)
const express = require('express');
const mongoose = require('mongoose');
const taskRoutes = require('./routes/tasks');
const cors = require('cors');
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
app.use('/api', taskRoutes);
mongoose.connect('mongodb://localhost:27017/todo-app', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Could not connect to MongoDB', err));
app.listen(port, () => {
console.log(Server is running on port ${port}
);
});
package.json
文件 (client/package.json)
{ "name": "todo-app-client", "version": "1.0.0", "main": "index.js", "dependencies": { "axios": "^0.21.1", "react": "^17.0.2", "react-dom": "^17.0.2", "react-scripts": "4.0.3" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" } }
package.json
文件 (server/package.json)
{ "name": "todo-app-server", "version": "1.0.0", "main": "app.js", "dependencies": { "cors": "^2.8.5", "express": "^4.17.1", "mongoose": "^5.12.3" }, "scripts": { "start": "node app.js" } }
`.gitignore`文件示例
Client side ignores client/node_modules/ client/dist/ client/build/ client/package-lock.json Server side ignores server/node_modules/ server/package-lock.json
到此,以上就是小编对于“app代码网站”的问题就介绍到这了,希望介绍的几点解答对大家有用,有任何问题和不懂的,欢迎各位朋友在评论区讨论,给我留言。
原创文章,作者:K-seo,如若转载,请注明出处:https://www.kdun.cn/ask/723229.html