这是我的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>我希望将pokemonname的值传递给node.js服务器端文件化server.js中的${passthevaluehere},该文件具有以下当前代码:
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});
});
});对前端和后端的开发仍然是新的。
发布于 2022-10-08 12:29:14
写这个答案时不需要对Nodejs视图引擎有很强的了解。在Nodejs中,我们有一些叫做中间件功能的东西。在中间件中,我们执行一些操作/验证,然后将其传递给下一个函数。在NodeJS中,它基本上如下所示:
route.get( getPokemon,searchPokemon);因此,getPokemon函数将执行一些操作,例如从html获取值,然后将数据传递给下一个函数以进行进一步的操作/验证。
为了传递使用res.pokemon = pokemonname /Notice的数据,我们在res/中创建了一个名为pokemon的新对象
现在,在searchPokemon函数中,我们使用res.pokemon /Here获取数据,res.pokemon是我们在前一个函数中创建的同一个对象。
一个示例如下所示:
router.get(verify,sendMess);
const verify=async(req,res,next)=>{
const pokemons=req.body;
if(pokemons) res.pokemonName=pokemons;
next(); /* To call the next function we have to use the next method available in the middlewares.*/
}
const sendMess=async(req,res)=>{
res.status(200).send(res.pokemonName);
}如果您仍然对使用中间件有一些疑问,那么看一下这些文档。
发布于 2022-10-08 12:32:22
将<input>字段和<button>放在<form>中,删除getPokemon函数和onclick,然后让按钮将整个表单提交到后端。
<form action="other" method="get">
<input type="search" id="default-search" name="searchterm" placeholder="Search Pokemon" required="">
<button type="submit" id="searchpokemon">Search</button>
</form>现在,按下按钮将导致浏览器用GET http://your.server/other?searchterm=<what the user typed in the search field>替换当前页面。换句话说:它重新加载当前页面,但使用不同的搜索项。
GET请求将调用您的server.js文件,其中您必须用${req.query.searchterm}替换(未定义的)变量${placethevaluehere}。
但是,您的other.ejs代码似乎没有使用title和data字段,因此新页面将与前一页完全相同。也许您没有共享other.ejs的完整代码。
https://stackoverflow.com/questions/73994660
复制相似问题