0

I'm trying to pass data (array) from node.js backend to frontend JS to process it there. 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.

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?

6
  • A server cannot send data to the client without the client requesting it. The client should fetch the data. Commented May 7, 2021 at 18:09
  • 1
    The client JS should use AJAX to request the data. Commented May 7, 2021 at 18:10
  • Your web page should use AJAX to make the /search-db API request to your server. 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. Also, unrelated, your findInDb function should return the search results instead of placing them in a global variable (searchResults). Example here. Commented May 7, 2021 at 18:12
  • @jarmod I actually use just form to generate URL with query parameter and use req.query to get this query param, then use it to search db. So I need to start with fetch and find the way to send query parameter with fetch? Commented May 7, 2021 at 18:24
  • Yes, collect the data you need in the web page and then use fetch, rather than doing your typical POST. You can issue POST or GET (or other) with fetch, as you need to. Commented May 7, 2021 at 18:36

1 Answer 1

1

Your web page can use AJAX via fetch to make the /search-db API request to your server. 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.

Example: How to create a REST API with Express.js in Node.js

Also, unrelated, your findInDb function should return the search results instead of placing them in a global variable (searchResults).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.