Heroku Postgres: Unhandled rejection Error: self signed certificate - node.js

I'm trying to configure the PostgreSQL database with postgrator in node, using the connectionString in production. I've added the code for initialization in node
const postgrator = new Postgrator(migrationConfig);
postgrator.migrate('002', (err, migrations) => {
if (err) {
console.error(err);
} else {
console.log(migrations);
}
postgrator.endConnection();
});
const isDevelopment = process.env.NODE_ENV === 'development';
let migrationConfig;
if (isDevelopment) {
migrationConfig = {
"migrationDirectory": "migrations",
"driver": "pg",
"host": process.env.DEV_DB_HOST,
"port": process.env.DEV_DB_PORT,
"database": process.env.DEV_DB_DATABASE,
"username": process.env.DEV_DB_USER,
"password": process.env.DEV_DB_PASS,
"ssl": !isDevelopment,
}
} else {
migrationConfig = {
"migrationDirectory": "migrations",
"driver": "pg",
"connectionString": process.env.DATABASE_URL,
"ssl": true,
}
}
I'm not sure why I'm getting the self signed certificate error on production.
2020-10-18T10:04:49.845485+00:00 app[web.1]: > export NODE_ENV=production && nodemon src/server.js
2020-10-18T10:04:49.845485+00:00 app[web.1]:
2020-10-18T10:04:50.082326+00:00 app[web.1]: [nodemon] 2.0.4
2020-10-18T10:04:50.083611+00:00 app[web.1]: [nodemon] to restart at any time, enter `rs`
2020-10-18T10:04:50.084275+00:00 app[web.1]: [nodemon] watching path(s): *.*
2020-10-18T10:04:50.084383+00:00 app[web.1]: [nodemon] watching extensions: js,mjs,json
2020-10-18T10:04:50.085033+00:00 app[web.1]: [nodemon] starting `node src/server.js`
2020-10-18T10:04:50.489740+00:00 app[web.1]: Express is listening on port 48474
2020-10-18T10:04:50.535273+00:00 app[web.1]: Unhandled rejection Error: self signed certificate
2020-10-18T10:04:50.535275+00:00 app[web.1]: at TLSSocket.onConnectSecure (_tls_wrap.js:1502:34)
2020-10-18T10:04:50.535276+00:00 app[web.1]: at TLSSocket.emit (events.js:314:20)
2020-10-18T10:04:50.535276+00:00 app[web.1]: at TLSSocket._finishInit (_tls_wrap.js:937:8)
2020-10-18T10:04:50.535277+00:00 app[web.1]: at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:711:12)
2020-10-18T10:04:51.077573+00:00 heroku[web.1]: State changed from starting to up
I've upgraded the dyno to a paid service to activate the SSL, yet this error still continues to come up. I saw online suggestin to set rejectUnauthorized to false`, but postgrator does not provide that option. Even if I set it to the Postgres configuration the issue seems to still persist.
How do I fix this?

Related

Firbase/Heroku/Node JS - Firebase Invalid Credential / failed to parse service account json file / ENAMETOOLONG

I'm using github actions to deploy my first webapp via Heroku.
My code:
const fireBaseAdmin = require('firebase-admin');
if (!fireBaseAdmin)
throw new Error('The FIREBASE_SERVICE_ACCOUNT_CREDS environment variable was not found!');
fireBaseAdmin.initializeApp({
"credential": fireBaseAdmin.credential.cert(JSON.stringify({
"type": process.env.FIREBASE_TYPE,
"project_id": process.env.FIREBASE_PROJECT_ID,
"private_key_id": process.env.FIREBASE_PRIVATE_KEY_ID,
"private_key": process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'),
"client_email": process.env.FIREBASE_CLIENT_EMAIL,
"client_id": process.env.FIREBASE_CLIENT_ID,
"auth_uri": process.env.FIREBASE_AUTH_URI,
"token_uri": process.env.FIREBASE_TOKEN_URI,
"auth_provider_x509_cert_url": process.env.FIREBASE_AUTH_PROVIDER,
"client_x509_cert_url": process.env.FIREBASE_CLIENT
}))
});
module.exports = fireBaseAdmin;
Each of the .env variables are stored in Heroku's Config Vars.
Error log from Heroku (I stripped sensitive tokens/keys):
2021-08-17T11:16:53.818119+00:00 app[web.1]: /app/node_modules/firebase-admin/lib/credential/credential-internal.js:151
2021-08-17T11:16:53.818149+00:00 app[web.1]: throw new error_1.FirebaseAppError(error_1.AppErrorCodes.INVALID_CREDENTIAL, 'Failed to parse service account json file: ' + error);
2021-08-17T11:16:53.818150+00:00 app[web.1]: ^
2021-08-17T11:16:53.818150+00:00 app[web.1]:
2021-08-17T11:16:53.818166+00:00 app[web.1]: FirebaseAppError: Failed to parse service account json file: Error: ENAMETOOLONG: name too long, open '{
"type":"service_account",
"project_id":"ec31",
"private_key_id":"2900d",
"private_key":"-----BEGIN PRIVATE KEY-----\nQ=\n-----END\nPRIVATE KEY-----\n",
"client_email":"firebase-adminsdk-.gserviceaccount.com",
"client_id":"10",
"auth_uri":"https://accounts.google.com/o/oauth2/auth",
"token_uri":"https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url":"ttps://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url":"https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-o.gserviceaccount.com"
}'
2021-08-17T11:16:53.818167+00:00 app[web.1]: at FirebaseAppError.FirebaseError [as constructor] (/app/node_modules/firebase-admin/lib/utils/error.js:44:28)
2021-08-17T11:16:53.818168+00:00 app[web.1]: at FirebaseAppError.PrefixedFirebaseError [as constructor] (/app/node_modules/firebase-admin/lib/utils/error.js:90:28)
2021-08-17T11:16:53.818168+00:00 app[web.1]: at new FirebaseAppError (/app/node_modules/firebase-admin/lib/utils/error.js:125:28)
2021-08-17T11:16:53.818169+00:00 app[web.1]: at Function.ServiceAccount.fromPath (/app/node_modules/firebase-admin/lib/credential/credential-internal.js:151:19)
2021-08-17T11:16:53.818169+00:00 app[web.1]: at new ServiceAccountCredential (/app/node_modules/firebase-admin/lib/credential/credential-internal.js:67:28)
2021-08-17T11:16:53.818174+00:00 app[web.1]: at Object.exports.cert (/app/node_modules/firebase-admin/lib/credential/credential.js:34:54)
2021-08-17T11:16:53.818174+00:00 app[web.1]: at Object.<anonymous> (/app/firebase/index.js:25:42)
2021-08-17T11:16:53.818175+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:1072:14)
2021-08-17T11:16:53.818175+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
2021-08-17T11:16:53.818175+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:937:32)
2021-08-17T11:16:53.818176+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:778:12)
2021-08-17T11:16:53.818176+00:00 app[web.1]: at Module.require (internal/modules/cjs/loader.js:961:19)
2021-08-17T11:16:53.818177+00:00 app[web.1]: at require (internal/modules/cjs/helpers.js:92:18)
2021-08-17T11:16:53.818177+00:00 app[web.1]: at Object.<anonymous> (/app/middlewares/auth.js:1:15)
2021-08-17T11:16:53.818177+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:1072:14)
2021-08-17T11:16:53.818178+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10) {
2021-08-17T11:16:53.818178+00:00 app[web.1]: errorInfo: {
2021-08-17T11:16:53.818178+00:00 app[web.1]: code: 'app/invalid-credential',
2021-08-17T11:16:53.818190+00:00 app[web.1]: message: `Failed to parse service account json file: Error: ENAMETOOLONG: name too long, open '{
"type":"service_account",
"project_id":"e1",
"private_key_id":"2900",
"private_key":"-----BEGIN PRIVATE KEY-----\\nMIIEMoQ=\\n-----END\\nPRIVATE KEY-----\\n",
"client_email":"firebase-adminsdk-od.gserviceaccount.com",
"client_id":"1",
"auth_uri":"https://accounts.google.com/o/oauth2/auth",
"token_uri":"https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url":"ttps://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url":"https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-o.gserviceaccount.com"
}'`
2021-08-17T11:16:53.818190+00:00 app[web.1]: },
2021-08-17T11:16:53.818190+00:00 app[web.1]: codePrefix: 'app'
2021-08-17T11:16:53.818191+00:00 app[web.1]: }
2021-08-17T11:16:53.947406+00:00 heroku[web.1]: Process exited with status 1
2021-08-17T11:16:54.345497+00:00 heroku[web.1]: State changed from starting to crashed
I've been attempted to update my code based on the various posts on Stack Overflow but I'm not having success with solving the error. Here's a short list of the post I've been referencing:
Deploying Firebase App with Service Account to Heroku (environment variables with dotenv)
Authenticating with the Firebase Admin SDK using environment variable
Node.js -Firebase Service Account Private Key won't parse
Firebase: Failed to parse service account: 'project_id' must be set
Any assistance would be greatly appreciated!
The cert() method expects either the path to serviceAccount.json file (string) or a ServiceAccount object. Here you are entering a string so it's expecting that to be the path to serviceAccount.json and not stringified credentials and hence you get the error FirebaseAppError: Failed to parse service account json file. Try this:
fireBaseAdmin.initializeApp({
credential: admin.credential.cert({
type: process.env.FIREBASE_TYPE,
project_id: process.env.FIREBASE_PROJECT_ID,
private_key_id: process.env.FIREBASE_PRIVATE_KEY_ID,
private_key: process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'),
client_email: process.env.FIREBASE_CLIENT_EMAIL,
client_id: process.env.FIREBASE_CLIENT_ID,
auth_uri: process.env.FIREBASE_AUTH_URI,
token_uri: process.env.FIREBASE_TOKEN_URI,
auth_provider_x509_cert_url: process.env.FIREBASE_AUTH_PROVIDER,
client_x509_cert_url: process.env.FIREBASE_CLIENT
}),
databaseURL: `https://${process.env.FIREBASE_PROJECT_ID}.firebaseio.com/`
})

Deploy Node, Express, and MongoDB server to heroku

I created a server using Node, Express, and MongoDB Atlas. Here is the code of this:
server.js:
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
// model
let Cards = require('./models/cards.model');
// App config
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
// DB config
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true });
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection has been established successfully.");
})
// API Endpoints
// POST parameter
app.post('/tinder/cards', (req, res) => {
const card = req.body;
Cards.create(card, (err, data) => {
if(err){
return res.status(500).send(err)
} else {
return res.status(200).send(data)
}
})
})
// GET parameter
app.get('/', (req, res) => {
return res.status(200).send("Welcome to Tinder Clone Backend with NodeJS, ExpressJS, and MongoDB!!!")
})
app.get('/tinder/cards', (req, res) => {
Cards.find((err, data) => {
if(err) {
return res.status(500).send(err);
} else {
return res.status(200).send(data)
}
})
});
// Listener
app.listen(port, () => {
console.log(`Server is running on port ${port}`)
});
package.json
{
"name": "tinder-backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"mongoose": "^5.12.2"
}
}
cards.model.js
// creating database schema using mongoose
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const cardsSchema = new Schema({
name: String,
imgUrl: String
});
const Cards = mongoose.model('Cards', cardsSchema);
module.exports = Cards;
It is working locally and all endpoints sending and receiving data from mongodb atlas.
when I run this command in terminal to start the local server:
$ nodemon server
it is showing this:
[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
Server is running on port 5000
MongoDB database connection has been established successfully.
This means that my local server is running well and when I check in my browser and type in my server link i.e http://localhost:5000/tinder/cards, it showing data that I have posted previously:
[
{
"_id": "605a53881dedb514dcc1c4f2",
"name": "Elon Musk",
"imgUrl": "https://s3.india.com/wp-content/uploads/2020/03/Elon-Musk-AP.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4f3",
"name": "Shakira",
"imgUrl": "https://ichef.bbci.co.uk/news/976/cpsprodpb/738B/production/_116497592_gettyimages-971720370.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4f4",
"name": "Jeff Bezos",
"imgUrl": "https://media.wired.com/photos/6019cab23453f789506008d0/master/pass/Sec_Bezos_1036084400.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4f5",
"name": "Dua Lipa",
"imgUrl": "https://assets.vogue.com/photos/5f48136693122510d16f0352/4:3/w_1080,h_810,c_limit/118520052_586967341971321_6121798062289952442_n.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4f6",
"name": "Pitbull",
"imgUrl": "https://vz.cnwimg.com/wp-content/uploads/2010/03/Pitbull.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4f7",
"name": "Ellen",
"imgUrl": "https://www.geo.tv/assets/uploads/updates/2021-03-18/340307_5260100_updates.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4f8",
"name": "Bill Gates",
"imgUrl": "https://www.incimages.com/uploaded_files/image/1920x1080/getty_1185999101_20001333200092800_443629.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4f9",
"name": "Taylor Swift",
"imgUrl": "https://static.onecms.io/wp-content/uploads/sites/20/2020/12/02/taylor-swift1.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4fa",
"name": "Engin Altan",
"imgUrl": "https://www.incpak.com/wp-content/uploads/2020/09/50094085_2224186024567959_693900883193935752_n.jpg",
"__v": 0
},
{
"_id": "605a53881dedb514dcc1c4fb",
"name": "Esra Bilgic",
"imgUrl": "https://i.dawn.com/large/2021/01/6007fbceb61de.png",
"__v": 0
}
]
But when I deployed the same server to heroku, it is showing an empty object when I testing it.
When I run this command into my terminal:
$ heroku logs --tails
It is showing this error:
2021-03-25T11:08:08.715303+00:00 app[web.1]: (node:21) UnhandledPromiseRejectionWarning: MongooseServerSelectionError: Could not connect to
any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted.
Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/
2021-03-25T11:08:08.715323+00:00 app[web.1]: at NativeConnection.Connection.openUri (/app/node_modules/mongoose/lib/connection.js:839:32)
2021-03-25T11:08:08.715324+00:00 app[web.1]: at /app/node_modules/mongoose/lib/index.js:348:10
2021-03-25T11:08:08.715326+00:00 app[web.1]: at /app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:5
2021-03-25T11:08:08.715326+00:00 app[web.1]: at new Promise (<anonymous>)
2021-03-25T11:08:08.715327+00:00 app[web.1]: at promiseOrCallback (/app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:30:10)
2021-03-25T11:08:08.715328+00:00 app[web.1]: at Mongoose._promiseOrCallback (/app/node_modules/mongoose/lib/index.js:1152:10)
2021-03-25T11:08:08.715328+00:00 app[web.1]: at Mongoose.connect (/app/node_modules/mongoose/lib/index.js:347:20)
2021-03-25T11:08:08.715329+00:00 app[web.1]: at Object.<anonymous> (/app/server.js:23:10)
2021-03-25T11:08:08.715329+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:1063:30)
2021-03-25T11:08:08.715329+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
2021-03-25T11:08:08.715330+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:928:32)
2021-03-25T11:08:08.715330+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:769:14)
2021-03-25T11:08:08.715331+00:00 app[web.1]: at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
2021-03-25T11:08:08.715331+00:00 app[web.1]: at internal/main/run_main_module.js:17:47
2021-03-25T11:08:08.715332+00:00 app[web.1]: (Use `node --trace-warnings ...` to show where the warning was created)
2021-03-25T11:08:08.721117+00:00 app[web.1]: (node:21) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated
either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To term
inate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html
#cli_unhandled_rejections_mode). (rejection id: 1)
2021-03-25T11:08:08.721508+00:00 app[web.1]: (node:21) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the fut
ure, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
my server that is deployed on heroku is showing empty object instead of that data that I have posted,
when I type URL of heroku server i.e https://tinder-clone-backend-mern.herokuapp.com/tinder/cards :
{}
How can I make this server work perfectly as the local server does?
Try setting IPS, in your Atlas cluster/Network Access, to be available for all IPS (0.0.0.0/0) Let me know if it fixes.

Heroku would not connect to MongoDB Atlas

I know this question had been asked before, but I'm seriously not finding an answer to this issue anywhere.
I deployed a Node.js app to Heroku successfully, but I cannot connect to my MongoDB Atlas cluster.
This is the error I get:
2020-04-07T10:39:20.723516+00:00 app[web.1]: Connection failed... MongooseError [MongooseServerSelectionError]: connection <monitor> to 54.72.180.237:27017 closed
2020-04-07T10:39:20.723526+00:00 app[web.1]: at new MongooseServerSelectionError (/app/node_modules/mongoose/lib/error/serverSelection.js:22:11)
2020-04-07T10:39:20.723527+00:00 app[web.1]: at NativeConnection.Connection.openUri (/app/node_modules/mongoose/lib/connection.js:808:32)
2020-04-07T10:39:20.723529+00:00 app[web.1]: at Mongoose.connect (/app/node_modules/mongoose/lib/index.js:333:15)
2020-04-07T10:39:20.723530+00:00 app[web.1]: at Object.<anonymous> (/app/index.js:22:4)
2020-04-07T10:39:20.723531+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:959:30)
2020-04-07T10:39:20.723531+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
2020-04-07T10:39:20.723532+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:815:32)
2020-04-07T10:39:20.723532+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:727:14)
2020-04-07T10:39:20.723532+00:00 app[web.1]: at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
2020-04-07T10:39:20.723533+00:00 app[web.1]: at internal/main/run_main_module.js:17:11 {
2020-04-07T10:39:20.723533+00:00 app[web.1]: message: 'connection <monitor> to 54.72.180.237:27017 closed',
2020-04-07T10:39:20.723534+00:00 app[web.1]: name: 'MongooseServerSelectionError',
2020-04-07T10:39:20.723534+00:00 app[web.1]: reason: TopologyDescription {
2020-04-07T10:39:20.723535+00:00 app[web.1]: type: 'ReplicaSetNoPrimary',
2020-04-07T10:39:20.723535+00:00 app[web.1]: setName: null,
2020-04-07T10:39:20.723535+00:00 app[web.1]: maxSetVersion: null,
2020-04-07T10:39:20.723536+00:00 app[web.1]: maxElectionId: null,
2020-04-07T10:39:20.723536+00:00 app[web.1]: servers: Map {
2020-04-07T10:39:20.723537+00:00 app[web.1]: 'milenskiblog-shard-00-00-lkwi4.mongodb.net:27017' => [ServerDescription],
2020-04-07T10:39:20.723537+00:00 app[web.1]: 'milenskiblog-shard-00-01-lkwi4.mongodb.net:27017' => [ServerDescription],
2020-04-07T10:39:20.723538+00:00 app[web.1]: 'milenskiblog-shard-00-02-lkwi4.mongodb.net:27017' => [ServerDescription]
2020-04-07T10:39:20.723539+00:00 app[web.1]: },
2020-04-07T10:39:20.723539+00:00 app[web.1]: stale: false,
2020-04-07T10:39:20.723539+00:00 app[web.1]: compatible: true,
2020-04-07T10:39:20.723540+00:00 app[web.1]: compatibilityError: null,
2020-04-07T10:39:20.723540+00:00 app[web.1]: logicalSessionTimeoutMinutes: null,
2020-04-07T10:39:20.723541+00:00 app[web.1]: heartbeatFrequencyMS: 10000,
2020-04-07T10:39:20.723541+00:00 app[web.1]: localThresholdMS: 15,
2020-04-07T10:39:20.723541+00:00 app[web.1]: commonWireVersion: null
2020-04-07T10:39:20.723542+00:00 app[web.1]: },
2020-04-07T10:39:20.723542+00:00 app[web.1]: [Symbol(mongoErrorContextSymbol)]: {}
2020-04-07T10:39:20.723542+00:00 app[web.1]: }
This is how I connect to MongoDB:
mongoose
.connect(process.env.blog_db, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log("Connected to MongoDB..."))
.catch((err) => console.error(`Connection failed...`, err));
And this is my environment variable (which I set exactly the same in Heroku).
The weird thing is, if I run nodemon index.js the app runs perfectly and it connects to the MongoDB Atlas cluster immediately, but the deployed heroku app doesnt seem to connect to the DB.
I am literally out of ideas and I'm plucking my hair here, so please if anyone had tackled this issue before, I need your help!
Thanks in advance!

Encrypt pdf file using node-qpdf

I am trying to use node-qpdf
I just did simple:
Test.pdf is inside directory where index.js is
var qpdf = require('node-qpdf');
var options = {
keyLength: 128,
password: 'test123',
restrictions: {
print: 'low',
useAes: 'y'
}
}
var localFilePath ='Test.pdf';
var outputFilePath ='test';
qpdf.encrypt(localFilePath, options, outputFilePath);
I am getting error like:
Run: nodemon index.js
[nodemon] 2.0.2
[nodemon] to restart at any time, enter `rs`
[nodemon] watching dir(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node index.js`
C:\Users\Rad\Desktop\node-qpdf-master\test\node_modules\node-qpdf\index.js:56
return callback(null, outputStream);
^
TypeError: callback is not a function
at Object.Qpdf.encrypt (C:\Users\Rad\Desktop\node-qpdf-master\test\node_modules\node-qpdf\index.js:56:16)
at Object.<anonymous> (C:\Users\Rad\Desktop\node-qpdf-master\test\index.js:13:6)
at Module._compile (internal/modules/cjs/loader.js:945:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:962:10)
at Module.load (internal/modules/cjs/loader.js:798:32)
at Function.Module._load (internal/modules/cjs/loader.js:711:12)
at Function.Module.runMain (internal/modules/cjs/loader.js:1014:10)
at internal/main/run_main_module.js:17:11
[nodemon] app crashed - waiting for file changes before starting...
I think they haven't updated the docs, I read their codes, you must put outputFile and change your options into like this.
var options = {
keyLength: 256,
password: '12345',
outputFile: '<your output name file>',
restrictions: {
modify: 'none',
extract: 'n'
}
var doc = await qpdf.encrypt(`${fileLocation}.pdf`, options)

Node.js and Sendgrid mailer error on res.end

I'm a bit new to node. I'm using express and the sendgrid api to send an email (collected REST-fully). After sendgrid succeeds or fails, I want to respond with a json object. Here's the sample case:
var SendGrid = require('sendgrid-nodejs').SendGrid;
var sendgrid = new SendGrid(user, key);
app.get('/LGP/:email', function (req, res){
sendgrid.send({
to: req.params.email,
from: 'me#example.com',
subject: 'Hello World',
text: 'This email sent through SendGrid'
}, function(success, message) {
if (!success) {
console.log(message);
} else {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.write(JSON.stringify({ result: 'success' }));
res.end(); //error occurs: "Can't use mutable header APIs after sent."
}
}
);
});
On my local server (using foreman), everything works fine. But when I push it to heroku, it gives me this stack trace:
2013-02-27T22:12:46+00:00 app[web.1]: http.js:543
2013-02-27T22:12:46+00:00 app[web.1]: throw new Error("Can't use mutable header APIs after sent.");
2013-02-27T22:12:46+00:00 app[web.1]: ^
2013-02-27T22:12:46+00:00 app[web.1]: Error: Can't use mutable header APIs after sent.
2013-02-27T22:12:46+00:00 app[web.1]: at ServerResponse.getHeader (http.js:543:11)
2013-02-27T22:12:46+00:00 app[web.1]: at /app/node_modules/express/node_modules/connect/lib/middleware/logger.js:229:26
2013-02-27T22:12:46+00:00 app[web.1]: at ServerResponse.<anonymous> (/app/node_modules/express/node_modules/connect/lib/middleware/logger.js:149:20)
2013-02-27T22:12:46+00:00 app[web.1]: at /app/app.js:60:13
2013-02-27T22:12:46+00:00 app[web.1]: at IncomingMessage.<anonymous> (/app/node_modules/sendgrid/lib/sendgrid.js:74:9)
2013-02-27T22:12:46+00:00 app[web.1]: at IncomingMessage.emit (events.js:81:20)
2013-02-27T22:12:46+00:00 app[web.1]: at HTTPParser.onMessageComplete (http.js:133:23)
2013-02-27T22:12:46+00:00 app[web.1]: at CleartextStream.ondata (http.js:1213:22)
2013-02-27T22:12:46+00:00 app[web.1]: at CleartextStream._push (tls.js:291:27)
2013-02-27T22:12:46+00:00 app[web.1]: at SecurePair._cycle (tls.js:565:20)
2013-02-27T22:12:48+00:00 heroku[web.1]: Process exited with status 1
2013-02-27T22:12:48+00:00 heroku[web.1]: State changed from up to crashed
/app/app.js:60:13 refers to the line with "res.end()". What am I doing wrong?
To maximize your chances of your app behaving the same locally and on heroku, you should make sure you specify specific versions for all modules and avoid using "*" for the main dependencies.
Should also should specify the node version in package.json:
"engines": {
"node": "0.8.20"
}
(use whatever version is appropriate).

Resources