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

如何将EJS中pokemonname变量值传递至Node.js服务器端?

如何将EJS中的输入值传递到Node.js服务器端

问题背景

我是前后端开发新手,希望将EJS文件中变量pokemonname的值传递至Node.js服务器端的server.js文件中,替换${passthevaluehere}的位置。

原有代码

other.ejs

<input type="search" id="default-search" class="block p-4 pl-10 w-full text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="Search Pokemon" required="">
<button type="submit" id="searchpokemon" onclick="getPokemon()" class="text-white absolute right-2.5 bottom-2.5 bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-4 py-2 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">Search</button>

<script> function getPokemon() {
            const pokemonname = document.getElementById("default-search").value;
            //forchecking the value of pokemonname
            console.log(pokemonname)
        } </script>

server.js

var express = require('express');
var app = express();
var weather = require('weather-js');
const dayjs = require('dayjs')
var fetchUrl = require("fetch").fetchUrl;

app.set('view engine', 'ejs');

app.listen(3000)
app.get('/other', async function (req, res) {
    fetchUrl(`https://pokeapi.co/api/v2/pokemon/${passthevaluehere}`, function(error, meta, body){
        var meals = JSON.parse(body)
        var data = {
            url: req.url,
            itemData: meals
        }
        console.log(data.itemData)
        res.render('other', {title:'OtherAPI', data});
    });
    
});

解决方案

方法一:使用表单提交(无需额外JS逻辑,适合新手)

修改other.ejs,将输入框和按钮包裹在<form>标签内,通过GET请求直接传递参数:

<form action="/other" method="GET" class="relative">
    <input type="search" name="pokemonname" id="default-search" class="block p-4 pl-10 w-full text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="Search Pokemon" required="">
    <button type="submit" id="searchpokemon" class="text-white absolute right-2.5 bottom-2.5 bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-4 py-2 dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">Search</button>
</form>
  • 给输入框添加name="pokemonname",服务器通过这个名称获取参数
  • 表单的action="/other"指定提交到该路由,method="GET"会将参数拼接到URL中

方法二:修改JS函数跳转传递参数

如果保留原有的getPokemon函数,修改函数内容,通过URL查询参数传递值:

function getPokemon() {
    const pokemonname = document.getElementById("default-search").value;
    // 对参数编码,避免特殊字符问题
    const encodedName = encodeURIComponent(pokemonname);
    // 跳转到带查询参数的/other页面
    window.location.href = `/other?pokemonname=${encodedName}`;
}

服务器端修改(两种方法通用)

修改server.js中的/other路由,通过req.query.pokemonname获取前端传递的参数,并处理异常情况:

app.get('/other', async function (req, res) {
    // 获取前端传递的精灵名称,设置默认值避免空请求
    const pokemonName = req.query.pokemonname || 'pikachu';
    
    fetchUrl(`https://pokeapi.co/api/v2/pokemon/${pokemonName}`, function(error, meta, body){
        // 处理请求错误
        if (error) {
            console.error('请求Pokemon API失败:', error);
            return res.render('other', {title:'OtherAPI', data: {itemData: null}});
        }
        
        try {
            // 解析API返回的JSON数据
            const pokemonData = JSON.parse(body);
            const data = {
                url: req.url,
                itemData: pokemonData
            };
            
            console.log(data.itemData);
            res.render('other', {title:'OtherAPI', data});
        } catch (parseError) {
            // 处理JSON解析错误
            console.error('解析响应数据失败:', parseError);
            res.render('other', {title:'OtherAPI', data: {itemData: null}});
        }
    });
});
  • req.query.pokemonname:获取URL中?pokemonname=xxx的参数值
  • 添加错误处理,避免因参数错误或API请求失败导致服务器崩溃
  • 设置默认值pikachu,当用户未输入内容时也能正常请求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 00:05:32