当前位置: 首页 > news >正文

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


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

选择合适的托管服务

配置环境变量

处理安全问题

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

http://www.lryc.cn/news/537738.html

相关文章:

  • Flutter中 List列表中移除特定元素
  • DeepSeek从入门到精通(清华大学)
  • 动态规划:解决复杂问题的高效策略
  • 【kafka系列】Kafka事务的实现原理
  • 网络将内网服务转换到公网上
  • c#自动更新-源码
  • 爬虫实战:利用代理ip爬取推特网站数据
  • git使用,注意空格
  • 138,【5】buuctf web [RootersCTF2019]I_<3_Flask
  • docker 运行 芋道微服务
  • C++ Primer 函数重载
  • 【Rust中级教程】1.6. 内存 Pt.4:静态(static)内存与‘static生命周期标注
  • 【设计模式】【行为型模式】解释器模式(Interpreter)
  • 修改OnlyOffice编辑器默认字体
  • React echarts柱状图点击某个柱子跳转页面
  • wordpress主题插件开发中高频使用的38个函数
  • ElasticSearch基础和使用
  • qt-C++笔记之QGraphicsScene和 QGraphicsView中setScene、通过scene得到view、通过view得scene
  • 小白win10安装并配置yt-dlp
  • 【kafka系列】broker
  • 用大模型学大模型05-线性回归
  • Python实现AWS Fargate自动化部署系统
  • 国产编辑器EverEdit - 上下翻滚不迷路(历史编辑位置、历史光标位置回溯功能)
  • 今日写题work05
  • [C++语法基础与基本概念] std::function与可调用对象
  • 两个实用且热门的 Python 爬虫案例,结合动态/静态网页抓取和反爬策略,附带详细代码和实现说明
  • 华象新闻 | 2月20日前谨慎升级 PostgreSQL 版本
  • 跳跃游戏 II - 贪心算法解法
  • 图像质量评价指标-UCIQE-UIQM
  • CentOS上安装WordPress