user1943674 user1943674 - 1 year ago 115
Javascript Question

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!

Answer Source

All you need to do is add something like this:'/question/:number', function(req, res) {
    var qid = 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');