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

Express中AJAX POST传关键词数组时req.body.keywords为undefined的解决方法

问题描述

我用Node.js和Express开发了一个博客应用,通过数组存储博客文章,现在需要将关键词数组传递到app.post()方法中,保存包含关键词的博客文章。

我实现了前端脚本,将输入的关键词转为独立的span元素:

$("#keywordInput").on("keydown", function(event) {
        // "13"对应回车键
        if (event.which === 13) {
            const maxKeywords = 6;

            // 阻止输入框默认提交行为
            event.preventDefault(); 
            
            const keyword = $(this).val().trim();

            if(keyword !== "") {
                if ($('#keywordList .keyword').length < maxKeywords) {
                    const keywordTag = $('<span>').addClass('keyword').text(keyword);
    
                    $('#keywordList').append(keywordTag);
                    $(this).val(''); 
                }
                else {
                    alert("关键词数量不能超过6个。");
                    $(this).val('');
                }
            }
        }
    });

接着写了读取span文本生成数组并通过AJAX提交的脚本:

$('.submitBtn').on("click", () => {
        var keywordArray = []
        $('.keyword').each(function() {
            keywordArray.push($(this).text());
        });

        $.ajax({
            type: "POST",
            url: "/submit", 
            data: JSON.stringify({ keywords: keywordArray }), 
        });
    })

后端的app.post()函数:

app.post("/submit", (req, res) => {
    const newTitle = req.body['postTitle'];
    const titleExists = post_array.some(post => post.title === newTitle);
    if (titleExists) {
        res.render("partials/return.ejs");
    }
    else {
        const post = {
            keywords: req.body.keywords,
            title: req.body['postTitle'],
            content: req.body['postContent'],
            authors: req.body['postAuthor'],
            date: formattedDate,
        }
        post_array.push(post);
        const selectedPost = post_array[0];
        const data = {
            posts: post_array,
            selectedPost: selectedPost,
        }
        res.render("partials/viewPosts.ejs", data);
    }
});

目前遇到的问题是req.body.keywords返回undefined,希望得到正确传递数组的方法。


解决方案

req.body.keywords为undefined的核心原因是请求格式未正确声明、Express未配置JSON解析,同时需要注意表单其他字段的传递,修复步骤如下:

1. 为AJAX请求添加Content-Type声明

因为你用JSON.stringify()将数据转为了JSON格式,必须告诉服务器请求体的类型是JSON,否则Express无法正确解析。同时要把表单里的其他字段(比如标题、内容)一起传入AJAX:

$('.submitBtn').on("click", () => {
    var keywordArray = []
    $('.keyword').each(function() {
        keywordArray.push($(this).text());
    });

    // 收集所有需要提交的表单数据
    const postData = {
        keywords: keywordArray,
        postTitle: $('#postTitle').val(),
        postContent: $('#postContent').val(),
        postAuthor: $('#postAuthor').val()
    };

    $.ajax({
        type: "POST",
        url: "/submit", 
        data: JSON.stringify(postData), 
        contentType: "application/json", // 新增此行,指定请求体类型
        success: function() {
            // 请求成功后的处理,比如页面刷新
        }
    });
})

2. 在Express中配置JSON解析中间件

Express默认不会解析JSON格式的请求体,需要在路由定义前添加中间件配置:

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

// 配置JSON解析中间件,必须放在所有路由之前
app.use(express.json());

// 之后再定义你的/submit路由
app.post("/submit", (req, res) => {
    // ... 原有代码
});

完成以上两步后,req.body.keywords就能正确获取到前端传递的关键词数组,同时其他表单字段也能正常读取。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 19:32:44