Chris Moretti
Chris Moretti

Reputation: 607

ExpressJS GET and POST on same route

Basically I am trying to put together a questionnaire in Express JS with EJS as the renderer. I have the pages populated, one for each question. The pages can be accessed with static links using the app.get('/question/:number?', routes.questions); function. The part I am confused on is how can I also perform a POST using the same routes. When they complete question 1, I want to post the answer in a temporary location (variable), and also load the next question. There are 4 questions in total. When they complete the 4th question, a different submit button is on the html page...this button should take all 4 answers and save it in a json file locally on the filesystem.

I am hoping someone could put together a quick example of this using generic code to give me a hint on how to complete these. Once I get one working, I think the overall functionality should be much clearer to me. Thanks!

Upvotes: 0

Views: 515

Answers (1)

user5734311
user5734311

Reputation:

All you need to do is add something like this:

app.post('/question/:number', function(req, res) {
    var qid = Number(req.params.number);
    var answer = req.body.answer; // <input name="answer" .../>
    // store answer
    answers[qid] = answer;
    // load next question
    if (qid < 4) res.redirect('/question/' + (qid + 1));
    else res.redirect('/results');
});

Upvotes: 2

Related Questions