0

I am using express to Post form data to mongolabs and it's working fine, but I noticed that I am rendering my / page after the form posts instead of the /thanks page. I am using Express-Handlebars and it is using my /thanks template, but it's not actually changing the URL. Here is the code:

//get index view
app.get('/', function (req, res) {
    //ask Mongo for Form model
    Form.find({}, (err, data) => {
        if (err) throw err;
        res.render('index')
    });

});

app.post('/', urlencodedParser, (req, res) => {
    //get data from the view and add it to Mongo
    var newForm = Form(req.body).save((err, data) => {
        if (err) throw err;
        //jsonify the form data
        res.json(data);
    });
    res.redirect('/thanks', {form: req.body });
});

What can I do to ensure that I change URLs after posting data to my DB?

Sean Kelly
  • 901
  • 7
  • 27
  • AFAIK you can't send a json response and also a redirect. Where do you expect the data to go? – Jim B. Oct 28 '17 at 21:53
  • @JimBaldwin the data is posting to mlabs where I'm storing the data, and then I'd like to redirect to the /thanks page. The strange thing is I'm rendering the Thanks template with the data, but I'm not able to see it reflected in the URL. What would be your suggestion – Sean Kelly Oct 28 '17 at 21:56
  • I'm referring to the data you are returning in res.json. It seems unnecessary to send it back to the client if you are going to redirect. – Jim B. Oct 28 '17 at 22:00
  • @JimBaldwin I'm just experimenting. The form for Request Service. The Thanks page would say something like "Thanks you contacted form.name in the form.department department! We'll be in touch!" I'm just trying to get comfortable with posting in express. Ultimately, I'd like to pull the form data into a dashboard, so I'm dipping my toes in first to get a foundation in express – Sean Kelly Oct 28 '17 at 22:02
  • I see. There are several ways to accomplish this, but the closest to what you're trying to do might be to use flash messages to carry the data for your /thanks page to display. Take a look at express-flash and similar packages. – Jim B. Oct 28 '17 at 22:12
  • @JimBaldwin awesome -- will do! – Sean Kelly Oct 28 '17 at 22:28

0 Answers0