简体   繁体   English

是否可以将数据从节点 js 传递到前端 js 而不是 html?

[英]Is it possible to pass data from node js to frontend js and not to html?

I'm trying to pass data (array) from node.js backend to frontend JS to process it there.我正在尝试将数据(数组)从 node.js 后端传递到前端 JS 以在那里处理它。 I don't want to pass data directly to backend-served html file because I'd like to keep it clean and don't want to do any loops there etc.我不想将数据直接传递给后端服务的 html 文件,因为我想保持它干净并且不想在那里做任何循环等。

My backend part looks like this:我的后端部分如下所示:

app.get("/search-db", function (req, res) {
    const term = req.query.term;
    findInDb(term);
    res.redirect('/search', {
        searchResults: searchResults,
    });
})

async function findInDb(query) {
    const collection = await getDbCollection();
    await collection.find().forEach((item) => {
        console.log(item.artist);
        if (item.artist.includes(query) || item.name.includes(query)) {
            searchResults.push(item);
        }
    })
}

Is this possible or do I have to clutter my html and use loop there to process passed results?这是可能的还是我必须弄乱我的 html 并在那里使用循环来处理传递的结果?

Your web page can use AJAX via fetch to make the /search-db API request to your server.您的 web 页面可以通过fetch使用 AJAX 向您的服务器发出/search-db API 请求。 Your server route handler should fetch the results from the DB, then invoke res.send() to send a JSON response back to the client, rather than res.redirect() to redirect the client to a new page.您的服务器路由处理程序应该从数据库中获取结果,然后调用res.send()将 JSON 响应发送回客户端,而不是res.redirect()将客户端重定向到新页面。

Example: How to create a REST API with Express.js in Node.js示例:如何在 Node.js 中使用 Express.js 创建 REST API

Also, unrelated, your findInDb function should return the search results instead of placing them in a global variable ( searchResults ).此外,不相关的是,您的findInDb function 应该返回搜索结果,而不是将它们放在全局变量( searchResults )中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM