About this documentation node js v5 3

Page 85

Example 6-6. Rendering plaintext output app.get('/test', function(req, res){ res.type('text/plain'); res.send('this is a test'); });

Example 6-7. Adding an error handler // this should appear AFTER all of your routes // note that even if you don't need the "next" // function, it must be included for Express // to recognize this as an error handler app.use(function(err, req, res, next){ console.error(err.stack); res.status(500).render('error'); });

Example 6-8. Adding a 404 handler // this should appear AFTER all of your routes app.use(function(req, res){ res.status(404).render('not-found'); });

Processing Forms When you’re processing forms, the information from the forms will usually be in req.body (or occasionally in req.query). You may use req.xhr to determine if the request was an AJAX request or a browser request (this will be covered in depth in Chapter 8). See Examples 6-9 and 6-10. Example 6-9. Basic form processing // body-parser middleware must be linked in app.post('/process-contact', function(req, res){ console.log('Received contact from ' + req.body.name + ' <' + req.body.email + '>'); // save to database.... res.redirect(303, '/thank-you'); });

Example 6-10. More robust form processing // body-parser middleware must be linked in app.post('/process-contact', function(req, res){ console.log('Received contact from ' + req.body.name + ' <' + req.body.email + '>'); try { // save to database.... return res.xhr ?

Boiling It Down

www.it-ebooks.info

|

63


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.