When refactoring docxtemplater on the server, the request JSON object is no longer accessible in the doc.setData() method

I've been working on refactoring some code in my Node server to remove docxtemplater. The req.body json object is functioning properly and I can even print it inside the doc.setData() method. However, when I try to launch the server, I encounter this error:

firstName: data.firstName,
               ^      
TypeError: Cannot read property 'firstName' of undefined     

Below is the content of my docxtemplater.js file.

const express = require('express');
const Docxtemplater = require('docxtemplater');
const JSZip = require('jszip');
const fs = require('fs');
const path = require('path');
const bodyParser = require('body-parser');

function estateDoc (data) {

let content = fs.readFileSync(path.resolve(__dirname, 'docxGen.docx'), 'binary');

let zip = new JSZip(content);

let doc = new Docxtemplater();
doc.loadZip(zip);

doc.setData({
  firstName: data.firstName,
  lastName: data.lastName,
  middleName: data.middleName,
  suffix: data.suffix,
  socialSecurity: data.socialSecurity,
  address: data.address,
  telephone: data.telephone,
  heir: data.heir
});
try {
    doc.render()
}
catch (error) {
    var e = {
        message: error.message,
        name: error.name,
        stack: error.stack,
        properties: error.properties,
    }
    console.log(JSON.stringify({error: e}));
    throw error;
}
var buf = doc.getZip()
             .generate({type: 'nodebuffer'});
fs.writeFileSync(path.resolve(__dirname + '/doc-sender-catcher', 'output.docx'), buf)
};
estateDoc();

module.exports = {estateDoc};

Answer №1

For those who are just starting out with refactoring in node, remember not to declare your function and then call it before exporting and running it. I made the mistake of trying to run the function with an empty data argument on the last line...

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

The Twitter node reply script appears to be malfunctioning and does not effectively send replies

I have a Twitter script that is currently set up to tweet the selected user once they tweet, but it posts the reply as a new standalone tweet instead of replying directly underneath the original tweet. How can I modify it to actually reply to the user&apos ...

An Axios request will consistently return a HTTP status code of 200

I have encountered an issue with a PUT request I am making. Despite receiving a 404 response from my express server, axios always sees it as 200. The correct response is shown in the express logs: PUT /v1/org/password/reset 404 339.841 ms - 71 This is th ...

Dealing with nested dictionary values in columns using Python Pandas

My dataset includes a column called "data" that contains JSON objects as values, and I am looking to separate them. source = {'_id':['SE-DATA-BB3A','SE-DATA-BB3E','SE-DATA-BB3F'], 'pi':['BB3A_CAP_BMLS ...

Swift 2 JSON Call may potentially cause an error if not properly handled, even though it does not require the

Just recently, I made the switch to El Capitan beta 2 and Xcode 7 - beta as required. As a result, my app had to be updated to Swift 2, and that's when a new error popped up in relation to the json string. Here's a snippet of my code: let jsonDa ...

Unable to integrate an if/else statement into the JSON reply

Working with an API to retrieve data and display images from it. I am attempting to implement an if/else statement that will show photos if the search term yields results in the response, and display a message indicating no results if it does not. Curren ...

Exploring the capabilities of Ruby on Rails in conjunction with a JSON parser to

I am utilizing the 'gem json' to retrieve JSON data from a specified URL, for instance: "http://locallhost:3000/qwerty/give_json.json" along with {"one":"Omg","two":125,"three":"Hu"} Operating within my rails application class QwertyControlle ...

Android JSON Parsing Woes

Having trouble parsing this text as JSON. Initially, I created a jsonobject from a URL but I can't seem to display the data while debugging. Can someone please assist? JSON: [ { "Date":"21.12.2015", "Imsak":"05:51", "Gun ...

Top strategy for structuring nested classes in JSON feeds

Currently, I am utilizing the Facebook API in C# and leveraging the NewtonSoft JSON library to process all the data returned by the API. While working on retrieving a list of user pages, I often find myself creating custom classes for individual attribute ...

The JSON Deserialization method returned a value of 0

Greetings! I'm facing some challenges in C# (Xamarin) after following various tutorials on parsing. My main focus is on extracting the value only. Does anyone have any insights on how to resolve this issue? Below is a snippet of my JSON data: { &q ...

Solana protocol for initiating numerous lamport transactions and triggering event notifications

In the process of developing a software program designed to handle multiple payments through a single call, there are specific steps that need to be executed: Accept a set amount of lamports Distribute a portion of the received lamports to specified walle ...

Configuration for secondary dependencies in Tailwind

As per the guidelines outlined in the official documentation, it is recommended to configure Tailwind to scan reusable components for class names when using them across multiple projects: If you’ve created your own set of components styled with Tailwin ...

Fetching Data from Firebase Cloud Functions and Pass it to iOS Application

Having an issue with my Firebase Cloud Function setup for communication between Stripe and my iOS App. Even though console.log(customer) shows a valid customer JSON object, the iOS app seems to be receiving nil as the result. Could this be due to me retu ...

Parsing JSON data in a CodeIgniter PHP environment from React using AJAX

Currently, my React application is running on localhost:3000 while my CodeIgniter API is running on localhost:8000. I am attempting to send an AJAX post request and pass data in JSON format but I am unsure of how to receive it in my controller. Here is wh ...

Secure your controller functions by wrapping them with session values in a separate function

My system relies on session values to determine if a user is an admin. Currently, I am checking for this information in each controller function like so: exports.DeleteUser = function (req, res) { if(req.session == undefined || req.session.Lv < 80) ...

Ways to change a variable in one file using another

My log.js, var data ; var winston = require('winston'); var config = {'status':1}; module.exports.config = config; In the get.js file (where I intend to update log.js), exports.getcategories = function (req, res) { if(log.stat ...

What is the process for adding and modifying data within a database using Node.js?

I have developed a message schema and conversation schema, but I am facing difficulties with storing the data in MongoDB. messageschema.js: const mongoose = require('mongoose'); const Schema = mongoose.Schema; // Creating the Message Schema co ...

Ways to eliminate text following a string substitution

When running the code below with keys assigned to summer, spring, fall, and winter, the output for ins would be: ['req.body.summer, req.body.spring, req.body.fall, req.body.winter'] I need to eliminate the surrounding string from the replace co ...

How can you verify a successful connection in Mongoose.js?

Similar Question: is there a mongoose connect error callback I am currently using mongoose.createConnection to establish a connection, but it operates in async mode. Can someone please guide me on how to verify if the connection was successful and al ...

EJS variable not detected by Visual Studio IDE in JavaScript file

Working on a Node.js project with the express framework and utilizing EJS as the template engine, my IDE of choice is Visual Studio. Encountering an issue when using EJS variables within the same ejs file. Though it renders correctly and functions perfect ...

The data in AngularJS ng-repeat does not appear accurately

I've encountered an unusual issue while working with ng-repeat in combination with ui-router. To test this, I set up a simple markup that fetches data from my local node server and displays it using ng-repeat. During the test, I add a new row to the ...