What is the process of invoking a node module in an express-rendered view?

Struggling to comprehend how to pass data to my view. Currently integrating the Mozscape node module into an application and unsure of how to send the information to the view. My assumption is that I should create the object in the router, call the function in the view, then utilize Handlebars to iterate through the data?

Below is the code snippet from my router:

// Express
const express = require('express');
// Router for index view
const index   = express.Router();

// Mozscapes SEO data
var Mozscape = require('mozscape').Mozscape;

// Accessid and secretid required by Mozscape
// Only one call allowed every 10 seconds with free plan
// Need to add to env file later
var moz = new Mozscape('mozscape-6d6ab44235', '846aca62a6db69661c81b784115e8a9');

// Dummy business data
var business =
    {
        name:       'Party Corner',
        address:    '123 Main Street, Red Bank, NJ',
        hours:      'Monday through Friday 9 - 5',
        website:    'http://www.partycorner.com/',
        category:   'Party Supplies',
        imgUrl:     'https://scontent.fewr1-3.fna.fbcdn.net/v/t31.0-8/14361226_10154547117788288_58127422291546970_o.jpg?oh=126b8240a8ac27dfb06b57ed51f4320e&oe=5A5A8FCC'
    };

// Middleware to process data for view
var businessSeo;
businessSeo = function (req, res, next) {
    req.businessSeo = moz.urlMetrics(business.website, ['page_authority', 'links', 'domain_authority'], function (err, res) {
        if (err) {
            console.log(err);
            return;
        }
        console.log('Requesting data from Moz');

        console.log(res);
        return res;
    });
};
index.use(businessSeo);
// Logging the data
console.log(businessSeo);

// Use declare router for HTTP methods
// GET request for index with request, response, next parameters
index.get('/', function (req, res, next) {

    // Render response from server using index view from declared path in app.js
    res.render('index', {
        title: "Business Directory",       
        business: business,
        body:
            {
                description: 'This is a business for the business directory, how neat is that?'
            },
        mozData: businessSeo
    })
});


module.exports = index;

Attempting to log the object on the front end but receiving error that moz is not defined. Considering moving the business object into its own variable (later queried response), placing the function directly in the router, and accessing the business website from there?

Expected output:

Object {pda: 24.123844872381643, uid: 187, upa: 33.43142060578742}

Answer №1

function saveSeoData(input) {
    seoInfo = input;
}

//no need for middleware to process data before displaying it

seoInfo = moz.urlMetrics(business.website, ['page_authority', 'links', 'domain_authority'], function (error, result) {
        if (error) {
            console.log(error);
            return;
        }
        console.log('retrieving data from moz');

        //console.log(result); saved the data into a variable
        saveSeoData(result);
    });

//using router for HTTP methods
//handling GET request for index with request, response, next parameters
index.get('/', function (request, response, next) {
    //data has been received!
    console.log(seoInfo);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering Metro Bundler crash issue following execution of react-native run-android command

I am facing an issue with the metro of my react native app crashing when using react-native run-android. I have come across solutions that involve updating the blacklist.js file in the metroconfig folder. However, I cannot find the blacklist.js in my metro ...

Creating controller functions for rendering a form and handling the form data

When developing a web application using Express.js, it is common to have separate controller functions for rendering forms and processing form data. For instance, if we want to import car data from the client side, we might implement the following approach ...

Displaying the structure of a MongoDB database using Express and Angular in a tabular format

I am looking to present the data from MongoDB in a table format using HTML along with Node.js, Express.js, and Angular.js. Currently, my approach is as follows: route.js app.get('/superhero', function(req, res) { superhero.superhero_list(r ...

Encountering an EAI_AGAIN error code while running npm install on a fresh project directory in an Ubuntu VPS

Current Setup: VPS running Ubuntu 20.04 LTS with NGINX & PM2 hosting a MEAN stack project in the root folder. Error Occurrence: To add another project, I created a new folder in the root directory and added code files, including package.json (without pack ...

Is there a way to streamline this query code that seems overly complex?

Could someone please assist me in simplifying this code? I am trying to shorten or simplify the query code by using a stored procedure, but I still need to include the details inside the "()" parentheses. I am new to Node.js and would appreciate any help. ...

Incorporating a delay into looped HTTP requests while effectively utilizing Promise.all to track their completion

Greetings! In my current project, I am trying to introduce a 50ms delay before each subsequent HTTP request is sent to the server. Additionally, I aim to incorporate a functionality that triggers after all requests have been successfully made. To better e ...

how can I enable pass-through functionality in express middleware?

Currently, I have a POST API endpoint named /users which is used to retrieve the list of users. The reason behind using POST instead of GET is because the request body can be quite large and it may not fit in the URL for a GET request. In this scenario, i ...

Crafting a MongoDB query to 'find' documents within a range of matching numbers

Currently, I am utilizing the MongoDB NodeJS driver to search for a particular set of posts in the database. My objective is to efficiently retrieve posts within a specific range, such as the 50th to 100th matching posts, and then present this informatio ...

Implement SSL Encryption for IONIC Mobile Apps or Angular Web Applications

I am just beginning my journey in this field. Currently, I am using the IONIC framework to develop an application. The backends, which include authentication, storage, and a database, are hosted on Firebase. Additionally, I utilize some third-party APIs a ...

Session cookies restricted to certain routes only

Currently, I am utilizing Connect.js in conjunction with the connect-session module to handle session cookies. One issue that I have come across is that Connect places a session cookie on all routes except for static files. The dilemma arises when processi ...

Failure occurs when attempting to install pods in an integrated development environment compared to

Currently encountering an issue while attempting to execute a pod update from the terminal within my Integrated VS-code environment on a react-native project. The error message received is as follows: node:internal/modules/cjs/loader:936 throw err; ^ ...

Error in Webpack 5: Main module not found - Unable to locate './src'

When trying to build only Express and gql server-related files separately using webpack5, an error occurs during the process. ERROR in main Module not found: Error: Can't resolve './src' in '/Users/leedonghee/Dropbox/Project/observe ...

Troubleshooting the issue of option tag failing to insert values into MongoDB with React and NodeJS

I am currently working on integrating the option value tags in my MERN project. However, I am facing an issue where nothing is being inserted into the database. As a beginner in learning MERN, I am struggling to identify the root cause of this problem. B ...

I am debating whether to retrieve individual items in vuex using getters, actions, and SQL queries

Apologies if this question seems a bit unusual, but I'm struggling to articulate it clearly. I am currently developing a basic fullstack application using Vue, Vuex, Express, and Postgresql. As I retrieve data from my database and display it on the ...

Retrieve the value of an express session on a different page in a NodeJS application

I'm facing an issue with setting a session value on app.get('/login', ()) and then not being able to retrieve that value on any other page besides the login page. I'm wondering if this is the expected behavior of express-session or if ...

Finding a solution for the network error encountered during the execution of XMLHttpRequest.send in the specified file path (...distfxcoreservermain.js:200

Having recently delved into Angular, I successfully completed the development of my angular web application. While using ng serve for production, everything ran smoothly. However, after incorporating angular universal and attempting npm run dev:ssr or np ...

What is the best way to format the information when using response.send() in express.js?

I need help with customizing the content I'm returning in the app.post() method. Is there a way to do this? Below is an example of the app.post() code: app.post("/",function(req,res){ const query = req.body.cityName; const cityName = query.charA ...

modifying the headers for each individual file stored within an amazon s3 bucket

I encountered a significant number of files with incorrect mimetypes in a bucket, and unfortunately none of them have an expires set. Is there a way to change all of them at once? Currently, I am utilizing Knox: https://github.com/LearnBoost/knox I am ...

struggling to integrate OAuth2 authentication in LoopBack

I am looking to set up an oauth2 server using loopback, after successfully implementing it with express. However, I am encountering some issues with loopback. Below is the code snippet for oauth2orize: var app = require('../../server/server'); / ...

Displaying the username in a dropdown button with React-Bootstrap and EJS

After users log in to my site, I'd like to display their username on a dropdown button using React-Bootstrap. How can this be achieved? This is how my code for the dropdown button currently looks: <DropdownButton title="Dropdown" id="bg-nested-dr ...