Search code examples
node.jsformsexpresspugbody-parser

How to link form data to a GET route


I am pretty sure I am royally messing this up but I am stuck, and have no choice but to ask.

I have this simple pug form:

form(id="searchForm", action="/search" method="POST")
        input(type="text" name="keyword")
        input(value='Submit', type='submit')

Grabbing the form input is no problem. Down below gets that done.

app.post('/search, (req, res) => {
    var keyword = req.body.keyword
    console.log(keyword) // returns user input
})

But this is where I am struggling. I simply want to take my form data and inject it into :keyword. Naturally, I also want that page to show up when I click submit.

app.get('/search/:keyword', (req, res) => {
    scraper
        .searchDictionary(req.params.keyword)
        .then(words => {
        res.json(words);
    });
})

Basically, this is crawler project that I have to finish, and this is a crucial part to its functionality. That get request works easy enough. If I directly type search/enter_keyword, I get all the scraped data in JSON format. So, that functionality works exactly as it needs to.

The problem is, I want the form input to somehow sync with that route, and basically fulfill that :keyword portion of my route. Sorry if that's not enough info or this is deemed not a good way to do things. Ask questions if need be.


Solution

  • You can redirect to the another route:

    app.post('/search, (req, res) => {
        var keyword = req.body.keyword;
        res.redirect('/search/' + keyword);
    })