首页 前端知识 对于简单的HTML、CSS、JavaScript前端,我们可以通过几种方式连接后端

对于简单的HTML、CSS、JavaScript前端,我们可以通过几种方式连接后端

2025-02-27 11:02:10 前端知识 前端哥 135 714 我要收藏


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.部署:

选择合适的托管服务

配置环境变量

处理安全问题

这是一个基本的前后端连接方案,你可以根据需要进行扩展和修改。

转载请注明出处或者链接地址:https://www.qianduange.cn//article/21718.html
标签
评论
会员中心 联系我 留言建议 回顶部
复制成功!