1. 使用Fetch API發送HTTP請求(最簡單的方式):
//home.html
// 示例:提交表單數據到后端
const submitForm = async (formData) => {try {const response = await fetch('http://your-backend-url/api/submit', {method: 'POST',headers: {'Content-Type': 'application/json',},body: JSON.stringify(formData)});if (!response.ok) {throw new Error('提交失敗');}const result = await response.json();alert('提交成功!');} catch (error) {console.error('Error:', error);alert('提交失敗,請重試');}
};// 使用示例
document.querySelector('form').addEventListener('submit', (e) => {e.preventDefault();const formData = {name: document.getElementById('name').value,major: document.getElementById('major').value,studentId: document.getElementById('studentId').value,qq: document.getElementById('qq').value,message: document.getElementById('message').value};submitForm(formData);
});
2.簡單的后端服務器示例(Node.js?+ Express)。
//serve.js
const express = require('express');
const cors = require('cors');
const app = express();// 啟用CORS和JSON解析
app.use(cors());
app.use(express.json());// 處理表單提交
app.post('/api/submit', (req, res) => {const formData = req.body;// 這里可以添加數據庫操作console.log('收到的表單數據:', formData);// 返回響應res.json({success: true,message: '表單提交成功'});
});// 啟動服務器
const PORT = 3000;
app.listen(PORT, () => {console.log(`服務器運行在 http://localhost:${PORT}`);
});
3.如果需要數據庫支持,可以添加MongoDB:
//serve.js
const mongoose = require('mongoose');// 連接MongoDB
mongoose.connect('mongodb://localhost/309base', {useNewUrlParser: true,useUnifiedTopology: true
});// 定義數據模型
const Application = mongoose.model('Application', {name: String,major: String,studentId: String,qq: String,message: String,submitTime: { type: Date, default: Date.now }
});// 處理表單提交
app.post('/api/submit', async (req, res) => {try {const application = new Application(req.body);await application.save();res.json({success: true,message: '申請已保存'});} catch (error) {res.status(500).json({success: false,message: '保存失敗'});}
});
4.部署注意事項:
// 配置文件 config.js
const config = {development: {apiUrl: 'http://localhost:3000',mongoUrl: 'mongodb://localhost/309base'},production: {apiUrl: 'https://your-production-api.com',mongoUrl: process.env.MONGODB_URI}
};// 根據環境選擇配置
const env = process.env.NODE_ENV || 'development';
module.exports = config[env];
主要步驟:
1.前端:
使用Fetch API發送請求
處理響應和錯誤
添加加載狀態提示
2.后端:
設置基本的Express服務器
處理CORS問題
連接數據庫
處理請求和響應
3.數據庫:
選擇合適的數據庫(如MongoDB)
設計數據模型
處理數據存儲和查詢
4.部署:
選擇合適的托管服務
配置環境變量
處理安全問題
這是一個基本的前后端連接方案,你可以根據需要進行擴展和修改。