如何将HTML中的GET请求数据传递至后端Router?
Hey there! Let's get your search form working smoothly. First, I noticed a small issue in your HTML, then we'll finish up the router logic to handle the request properly.
1. Fix the Duplicate ID in Your HTML
You've got two elements with the same id="search" (the text input and submit button). IDs need to be unique in a page—this can cause weird behavior if you ever try to target these elements with JavaScript. Here's the corrected HTML:
<p> <form action="/search" method="GET" class="form-inline"> <div class="form-group"> <input type="text" name="search" id="search-input" placeholder="search..." class="form-control"> <input type="submit" value="search" id="search-submit" class="btn btn-default"> </div> </form> </p>
I renamed the IDs to search-input and search-submit to keep them unique, while keeping the name="search" intact—this is what the router will use to grab the input value.
2. Complete the Router Logic (Express.js Example)
Assuming you're using Express.js (since your router snippet looks like it), here's how you can handle the GET request, access the search parameter, and send back a response:
// Assuming this is part of your Express router setup router.get("/search", (req, res) => { // Grab the search value from the query string (since it's a GET request) const searchQuery = req.query.search; // If no search term was provided, send a friendly message if (!searchQuery) { return res.send("Please enter a search term!"); } // Here's where you'd add your actual search logic (e.g., query a database) // For example, let's simulate a search result: const searchResults = [ `Result 1 for "${searchQuery}"`, `Result 2 for "${searchQuery}"` ]; // Send back the results—you can send HTML, JSON, or render a template res.send(` <h2>Search Results for "${searchQuery}"</h2> <ul> ${searchResults.map(result => `<li>${result}</li>`).join("")} </ul> `); // Alternatively, if you're using a template engine like EJS: // res.render("search-results", { query: searchQuery, results: searchResults }); });
How It Works:
- When the user submits the form, the browser sends a GET request to
/search?search=USER_INPUT(whereUSER_INPUTis what they typed). - The router uses
req.query.searchto access that input value directly. - You can then use that value to run your search logic (database queries, API calls, etc.) and return the appropriate response.
内容的提问来源于stack exchange,提问作者Adrian Marica

