How can I change a hardcoded parameter into an input value by user and then render the result of the function to a new page?

Viewed 45

I am trying to create a really simple web app to search for books using ISBN. The site will have a text input for ISBN and a submit button. So basically a user can input an ISBN in the input box, hit submit and render a display page displaying the isbn, title, author, description, etc. I am using node-isbn from npm to help me link my code to isbn APIs. I just don't know how to implement node-isbn into my code.

Here's a link to node-isbn (https://www.npmjs.com/package/node-isbn).

//schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const BookSchema = new Schema ({

    isbn: Number,
    title: String,
    author: String,
    description: String
    });

module.exports = mongoose.model('Book', BookSchema);
//ejs
<form action="/display" methods="POST">
        <div>
            <label for="isbn">Enter ISBN</label>
            <input type="text" name="isbn" id="isbn" placeholder="enter ISBN">
            <button>Submit</button>
        </div>
    </form>
//app.js with hardcoded isbn# as parameter. How can I render the result of the code below (using app.get) to /display page?

isbn.resolve('0735619670', function (err, book) {
            if (err) {
                console.log('Book not found', err);
            } else {
                console.log('Book found ', book);
            }
        });
1 Answers

You could try using Cheerio, like this:

var fs = require('fs'), cheerio = require('cheerio');

//Display page
app.get("/display", function(req, res) {

  //Reading the template html
  fs.readFile(htmlPath, { encoding: 'utf8' }, function(error, data) {

    //Loading data through Cheerio
    var cheerioData = cheerio.load(data);
    //Requesting ISBN data
    isbn.resolve('0735619670', function(err, book) {
      if (err) {
        console.log('Book not found', err);
      } else {
        //Replacing element of class title, with the book title
        cheerioData(".title").html(book.title)
        //Sending the Cheerio HTML
        res.send(cheerioData.html())
      }
    })
  })
});
Related