You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何点击按钮将EJS模板中电影数据传至Express服务器并存库?

解决无表单场景下向Express服务器发送数据并存库的问题

别担心,这种不用表单、直接通过按钮点击发送数据的需求其实很常见,咱们分前端和后端两部分来一步步搞定:

第一步:前端用Fetch API发送JSON数据

你已经能通过点击按钮拿到电影的标题、评分和描述了,接下来只需要把这些数据打包成JSON格式,用fetch发送到后端的指定路由就行。示例代码如下:

// 绑定按钮点击事件
document.querySelector('.add-to-list-btn').addEventListener('click', async () => {
  // 获取你已经定位到的元素文本
  const title = document.querySelector('.movie-title').textContent.trim();
  const rating = document.querySelector('.movie-rating').textContent.trim();
  const description = document.querySelector('.movie-description').textContent.trim();

  // 构造要发送的数据对象
  const movieData = { title, rating, description };

  try {
    const response = await fetch('/api/add-movie', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json', // 告诉服务器请求体是JSON格式
      },
      body: JSON.stringify(movieData), // 把JS对象转为JSON字符串
    });

    if (response.ok) {
      alert('电影已成功添加到你的列表!');
      // 这里可以加一些UI反馈,比如隐藏按钮、更新列表等
    } else {
      const errorMsg = await response.text();
      alert(`添加失败:${errorMsg}`);
    }
  } catch (error) {
    console.error('请求出错:', error);
    alert('网络出错,请稍后重试');
  }
});

第二步:后端Express配置与路由处理

首先,你需要确保Express服务器已经配置了解析JSON请求体的中间件,不然req.body会是空的。在你的server.js里先加上这行关键配置:

const express = require('express');
const app = express();

// 必须添加这个中间件,才能解析前端发送的JSON请求体
app.use(express.json());

// 你的其他原有配置(比如模板引擎、静态文件)保持不变
app.set('view engine', 'ejs');
app.use(express.static('public'));

接下来,添加接收数据的POST路由,这里以MongoDB+Mongoose为例(如果用SQL数据库,逻辑类似,只是数据库操作语句不同):

先定义Movie数据模型(如果还没做的话)

在models/Movie.js中创建模型:

const mongoose = require('mongoose');

const movieSchema = new mongoose.Schema({
  title: { type: String, required: true },
  rating: { type: String, required: true },
  description: { type: String, required: true },
  // 如果需要关联用户,可以额外添加userId字段
});

module.exports = mongoose.model('Movie', movieSchema);

编写接收数据的POST路由

回到server.js中添加路由:

const Movie = require('./models/Movie');
// 确保你已经连接了数据库,比如 mongoose.connect('mongodb://localhost:27017/movieListDB')

app.post('/api/add-movie', async (req, res) => {
  try {
    // 从请求体中提取前端发送的数据
    const { title, rating, description } = req.body;

    // 可选:验证数据是否完整
    if (!title || !rating || !description) {
      return res.status(400).send('缺少必要的电影数据');
    }

    // 创建新电影文档并存入数据库
    const newMovie = new Movie({ title, rating, description });
    await newMovie.save();

    // 返回成功响应
    res.status(201).send('电影添加成功');
  } catch (error) {
    console.error('数据库操作出错:', error);
    res.status(500).send('服务器内部错误,请稍后重试');
  }
});

关键注意点

  • 前端请求的Content-Type必须设为application/json,否则后端无法正确解析请求体。
  • 后端必须配置express.json()中间件,这是处理JSON格式请求的核心。
  • 数据库操作尽量用async/await,避免回调地狱,同时要做好错误捕获。

这样一来,当用户点击按钮时,前端就会把电影数据发送到后端的/api/add-movie路由,后端接收后验证并存入数据库,完美解决你的需求!

内容的提问来源于stack exchange,提问作者Ali Ahmed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:18:56