Friday 9 June 2017

NodeJS: Use a pug template to display results

I have a method in a NodeJS app that handles scraping a URL, and when successful, saving that data in a Mongo database, and showing the results.

Main method:

//url parameter
app.get('/urls/', function(req, res) {

  var client = new MetaInspector(req.query.url, {
    timeout: 5000
  });

  client.on("fetch", function() {

    var imagesArray = [];
    var keywordsArray = [];
    var now = new Date();
    var dateVal = dateFormat(now, "mm/dd/yyyy h:MM:ss");


    for (var i = 0; i < client.images.length; i++) {
      // we only want jpgs. nothing else.
      if (client.images[i].indexOf('.jpg') > -1) {
        imagesArray.push({
          "image": client.images[i]
        })
      }
    }

    for (var i = 0; i < client.keywords.length; i++) {
      keywordsArray.push({
        "keyword": client.keywords[i]
      })
    }

    var newUrls = Urls({
      url: client.url,
      date_added: dateVal,
      keywords: req.body.keywords,
      author: client.author,
      description: client.description,
      ogTitle: client.ogTitle,
      ogDescription: client.ogDescription,
      image: client.image,
      images: imagesArray,
      keywords: keywordsArray
    });

    newUrls.save(function(err) {
      if (err) throw err;

      res.send('Success' + newUrls);
    });

  });

  client.on("error", function(err) {
    console.log(err);
  });

  client.fetch();

});

This all works well and good. But I'm using Pug and Express and have specific routes setup. I'd like instead of sending the newUrls obj to the res.send, have it go to a particular route and pass it to a particular pug template I already have setup:

// Route.js

var express = require('express');
var router = express.Router();
var Urls = require('../models/urlModel');
var Footer = require('../models/footerModel');

/* URL Saved Success Page */
router.get('/saved', function (req, res) {});
});

module.exports = router;

I've tried using the res.send method, but that doesn't work. Any suggestions on how to handle this?



via SerpicoLugNut

No comments:

Post a Comment