Creating a React eCommerce app, deployed on Firebase and Payment gateaway is integrated with stripe.
As soon as I place an order, I am supposed to push it to the backend, and again fetch it back to the front end to show the order details to the user.
This is the code in "Index.js" in "Functions" folder, which serves the API call:
const express = require('express');
const cors = require('cors');
const stripe = require("stripe")
("XXXXXXXX");
// API
// - App Config
const app = express();
// - Middlewears
app.use(cors({ origin: true }))
app.use(express.json());
// - API routes
app.get("/", (request, response) => response.status(200).send('hello world'))
app.post("/payments/create", async (request, response) => {
const total = request.query.total;
console.log("Payment Request Revieved for this amount ->", total)
const paymentIntent = await stripe.paymentIntents.create({
amount: total, // subunits of currency
currency: "usd",
});
// 201 - OK - Created Something
response.status(201).send({
clientSecret: paymentIntent.client_secret
});
})
// - Listen Command
exports.api = functions.https.onRequest(app)
These are the errors I'm getting in the browser debugger
It looks like you're using the development build of the Firebase JS SDK.
When deploying Firebase apps to production, it is advisable to only import
the individual SDK components you intend to use.
For the module builds, these are available in the following manner
(replace <PACKAGE> with the name of a component - i.e. auth, database, etc):
CommonJS Modules:
const firebase = require('firebase/app');
require('firebase/<PACKAGE>');
ES Modules:
import firebase from 'firebase/app';
import 'firebase/<PACKAGE>';
Typescript:
import firebase from 'firebase/app';
import 'firebase/<PACKAGE>';
./node_modules/firebase/dist/index.esm.js # index.ts:18
This:
v3:1 You may test your Stripe.js integration over HTTP. However, live Stripe.js integrations must use HTTPS.
Also this:
Failed to load resource: the server responded with a status of 400 ()
And these errors are showing in my VS code terminal:
(node:1700) UnhandledPromiseRejectionWarning: Error: This value must be greater than or equal to 1.
> at Function.generate (D:\WebDev\TutorialProjects\React\AmazonClone\amazon-clone\functions\node_modules\stripe\lib\Error.js:40:16)
> at IncomingMessage.<anonymous> (D:\WebDev\TutorialProjects\React\AmazonClone\amazon-clone\functions\node_modules\stripe\lib\StripeResource.js:203:33)
> at Object.onceWrapper (events.js:421:28)
> at IncomingMessage.emit (events.js:327:22)
> at endReadableNT (internal/streams/readable.js:1327:12)
> at processTicksAndRejections (internal/process/task_queues.js:80:21)
> (Use `node --trace-warnings ...` to show where the warning was created)
> (node:1700) 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 terminate 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)
> (node:1700) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
It sounds like you're not setting amount correctly, but you're suppressing the details of the Stripe API error response, which would make this more obvious. You should add some debug logging in your /payments/create handler. Check your Dashboard logs to see the full error details another way.
What is the request shape that your client app makes to your back end on that endpoint? You're using express.json() as though you expect some json-encoded POST body, but then your handler is looking at query parameters with request.query.total. Have you checked whether you're getting the expected value here?
You need to send an amount that is both >=1 and at least the minimum charge for your currency.
How to solve model.find() function produces "buffering timed out after ... ms"? I'm using mongoose v 5.11.0, npm v6.14.8 and mongodb v
Here's the code.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
const assert = require('assert');
var mongoose = require('mongoose');
try {
var db = mongoose.connect('mongodb://localhost:27017', {useNewUrlParser: true, dbName: 'swag-shop' });
console.log('success connection');
}
catch (error) {
console.log('Error connection: ' + error);
}
var Product = require('./model/product');
var WishList = require('./model/wishlist');
//Allow all requests from all domains & localhost
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "POST, GET");
next();
});
app.get('/product', function(request, response) {
Product.find({},function(err, products) {
if (err) {
response.status(500).send({error: "Could not fetch products. "+ err});
} else {
response.send(products);
}
});
});
app.listen(3004, function() {
console.log("Swag Shop API running on port 3004...");
});
The product model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var product = new Schema({
title: String,
price: Number,
likes: {type: Number, default: 0}
});
module.exports = mongoose.model('Product', product);
Additionally, running the file also produces the following warnings:
D:\Test\swag-shop-api>nodemon server.js
[nodemon] 2.0.6
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
success connection
Swag Shop API running on port 3004...
(node:28596) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The "url" argument must be of type string. Received type function ([Function (anonymous)])
at validateString (internal/validators.js:122:11)
at Url.parse (url.js:159:3)
at Object.urlParse [as parse] (url.js:154:13)
at module.exports (D:\Test\swag-shop-api\node_modules\mongoose\node_modules\mongodb\lib\url_parser.js:15:23)
at connect (D:\Test\swag-shop-api\node_modules\mongoose\node_modules\mongodb\lib\mongo_client.js:403:16)
at D:\Test\swag-shop-api\node_modules\mongoose\node_modules\mongodb\lib\mongo_client.js:217:7
at new Promise (<anonymous>)
at MongoClient.connect (D:\Test\swag-shop-api\node_modules\mongoose\node_modules\mongodb\lib\mongo_client.js:213:12)
at D:\Test\swag-shop-api\node_modules\mongoose\lib\connection.js:820:12
at new Promise (<anonymous>)
at NativeConnection.Connection.openUri (D:\Test\swag-shop-api\node_modules\mongoose\lib\connection.js:817:19)
at D:\Test\swag-shop-api\node_modules\mongoose\lib\index.js:345:10
at D:\Test\swag-shop-api\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:5
at new Promise (<anonymous>)
at promiseOrCallback (D:\Test\swag-shop-api\node_modules\mongoose\lib\helpers\promiseOrCallback.js:30:10)
at Mongoose._promiseOrCallback (D:\Test\swag-shop-api\node_modules\mongoose\lib\index.js:1135:10)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:28596) 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 terminate 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)
(node:28596) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I tried increasing the bufferTimeoutMS or disabling the bufferCommands but still it won't work.
According to Documentation found in this link: https://mongoosejs.com/docs/connections.html#buffering
Mongoose lets you start using your models immediately, without waiting for mongoose to establish a connection to MongoDB.
That's because mongoose buffers model function calls internally. This
buffering is convenient, but also a common source of confusion.
Mongoose will not throw any errors by default if you use a model
without connecting.
TL;DR:
Your model is being called before the connection is established. You need to use async/await with connect() or createConnection(); or use .then(), as these functions return promises now from Mongoose 5.
The issue on model.find() error: Operation products.find() buffering timed out after 10000ms" was resolved by removing the node_module folder, *.json files and reinstalling the mongoose module.
The issue on the warnings was resolved by following this instructions https://mongoosejs.com/docs/deprecations.html
Well, I encountered the same problem and had very similar code. I got the same error when sending a get request while testing.
Eventually, I found the solution that my localhost DB wasn't running at that moment. Though it's a foolish error, but I had a hard time finding it.
This error poped becuase you are trying to access models before creating the connection with the database
Always link your mongodbconnection file (if you have created) in app.js by
var mongoose = require('./mongoconnection');
or just keep mongodb connection code in app.js
For me was 100% MongoDB Atlas issue.
I've created a cluster in Sao Paulo that for some reason wasn't working as expected. I've deleted it, create a new one in AWS / N. Virginia (us-east-1) and everything started working again.
i'm using this function to connect to the db and avoid some warnings
mongoose.connect(
url,
{ useNewUrlParser: true, useUnifiedTopology: true },
function (err, res) {
try {
console.log('Connected to Database');
} catch (err) {
throw err;
}
});
just use 127.0.0.1 instead of localhost
mongoose.connect('mongodb://127.0.0.1:27017/myapp');
Or use family:4 in mongoose.connect method like that
mongoose.connect('mongodb://localhost:27017/TESTdb', {
family:4
})
.then(() => {
console.log('FINE');
})
.catch(() => {
console.log("BAD");
})
I had the same problem.
After a long search I was able to find it.
I created a new user in MongoDB atlas settings. I changed the MongoDB connection value with the new user.
Changing DNS setting to 8.8.8.8 or changing mongodb connection settings to 2.2.12 did not work.
In my case my i forgot to import db.config file in server.js file
There has been a change in mongoose v5^ the spaghetti code has been refactored, It now returns a promise that resolves to the mongoose singleton. so you don't have to do this.
// You don't have todo this
mongoose.connect('mongodb://localhost:27017/test').connection.
on('error', handleErr).
model('Test', new Schema({ name: String }));
// You can now do this instead
mongoose.connect('mongodb://localhost:27017/test').catch(err);
Check here for references
What's new in Mongoose v5^
If this doesn't work for you, you can then change your connection URL > Select your driver and version to v2.2.12 or later
First you should check in which port mongodb currently running.
Use this command to check that port
sudo lsof -iTCP -sTCP:LISTEN | grep mongo
If there you find different port rather than 27017, you should change it
I was having this issue only on deployed lambda functions and everything worked fine on my local. The following worked for me.
Delete node_modules folder.
npm install
commit/push the new package-lock.json file
merge / run cicd pipeline / deploy.
For me, the issue was node version. I was getting the same error with nodejs version 17.
After trying all the suggestions on this thread, stumbled upon this open issue. Tried downgrading node, but that did not work, finally uninstalled node 17 completely and installed node 16 and the problem was solved!
You can check your node version on Mac using node --version
This means that, mongo connection has not been established like others have mentioned, go through your code and see if perhaps you forgot to create a mongoConnect() function to connect with your atlas URI
the best way is to put your initialization in a function, connect to db before starting the server. use a combination of async and a condition to check if environment variables are there(incase db url is in env) here is a sample code.
const start = async () => {
if (!process.env.DB_URI) {
throw new Error('auth DB_URI must be defined');
}
try {
await mongoose.connect(process.env.DB_URI!, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
});
console.log('Server connected to MongoDb!');
} catch (err) {
throw new DbConnectionError();
console.error(err);
}
const PORT = process.env.SERVER_PORT;
app.listen(PORT, () => {
console.log(`Server is listening on ${PORT}!!!!!!!!!`);
});
};
start();
You should check if string connection is correct, because in my case I forgot to include the .env file in my proyect. This file contains string connection for my server in digital ocean.
MONGO_URI="mongodb+srv://server:gfhyhfyh.mongo.ondigitalocean.com/db_customers"
Right now, I'm running a docker with Cassandra on it. I have a javascript file that sits outside the docker that needs to connect to Cassandra. I've found a node package that interfaces w/ JS, called cassandra-driver. However, with the following code:
var cassandra = require('cassandra-driver');
var PlainTextAuthProvider = cassandra.auth.PlainTextAuthProvider;
const client = new cassandra.Client({
contactPoints: ['127.0.0.1:9042'],
localDataCenter: '127.0.0.1',
keyspace: 'wasabi_experiments',
authProvider: new PlainTextAuthProvider('cassandra', 'cassandra')
});
I get
(node:17836) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): NoHostAvailableError: All host(s) tried for query failed. First host tried, 127.0.0.1:9042: ArgumentError: localDataCenter was configured as '127.0.0.1', but only found hosts in data centers: [datacenter1]. See innerErrors.
(node:17836) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): NoHostAvailableError: All host(s) tried for query failed. First host tried, 127.0.0.1:9042: ArgumentError: localDataCenter was configured as '127.0.0.1', but only found hosts in data centers: [datacenter1]. See innerErrors.
How can I get this to work?
Your problem is that you're using the 127.0.0.1 as value for localDataCenter parameter, but it should be set not to the address of the machine, but to the name of the Cassandra data center - in your case this is datacenter1. Change the value of that parameter to datacenter1, and it will start to work.
It would be:
const { Client, auth } = require('cassandra-driver');
const client = new cassandra.Client({
contactPoints: ['127.0.0.1:9042'],
localDataCenter: 'datacenter1', // here is the change required
keyspace: 'wasabi_experiments',
authProvider: new auth.PlainTextAuthProvider('cassandra', 'cassandra')
});
client.connect();
P.S. I recommend to read documentation for Node.js driver, and also "Developing applications with DataStax drivers" guide.
try first with a Cassandra client, ensure Cassandra is working properly and you can access it. After that try with the code.
Also you can try to access the 127.0.0.1:9042 using telnet or netcat to see if the port is open and listening. You can use netstat too for this task.
Edit: I'm changing the question to suit my current understanding of the problem which has changed significantly.
Original Title: Nodegit seems to be asking for wrong credentials on push
When trying to push using nodegit nothing seems to work on Windows (while they work fine on Linux).
Using SSH
sshKeyFromAgent - error authenticating: failed connecting agent
sshKeyNew - credentials callback is repeatedly (looks like an infinite loop
but I can't be sure)
sshKeyMemoryNew: credentials is called twice and then node exits with no diagnostic (the exit and beforeExit events on process aren't signalled)
Using HTTPS
userpassPlaintextNew: [Error: unknown certificate check failure] errno: -17
Original question follows.
I'm trying to get nodegit to push and the following question seems to address this situation. However I'm not able to get it to work.
I've cloned a repository using SSH and when I try to push, my credentials callback is being called with user git and not motti (which is the actual git user).
try {
const remote = await repository.getRemote("origin");
await remote.push(["refs/head/master:refs/heads/master"], {
callbacks: {
credentials: (url, user) => {
console.log(`Push asked for credentials for '${user}' on ${url}`);
return git.Cred.sshKeyFromAgent(user);
}
}
});
}
catch(err) {
console.log("Error:", err);
}
I get the following output:
Push asked for credentials for 'git' on git#github.[redacted].net:motti/tmp.git
Error: { Error: error authenticating: failed connecting agent errno: -1, errorFunction: 'Remote.push' }
If I try to hardcode motti to the sshKeyFromAgent function the error changes to:
Error: { Error: username does not match previous request errno: -1, errorFunction: 'Remote.push' }
This my first time trying to programmatically use git so I may be missing something basic...
Answer for some questions from comments:
I'm running on windows 10
node v8.9.4
git version 2.15.0.windows.1
nodegit version 0.24.1
the user running node is my primary user which when I use for git in command line works correctly
Instead of using git.Cred.sshKeyFromAgent - you could use git.Cred.sshKeyNew and pass your username / keys along.
const fs = require('fs');
// ...
const username = "git";
const publickey = fs.readFileSync("PATH TO PUBLIC KEY").toString();
const privatekey = fs.readFileSync("PATH TO PRIVATE KEY").toString();
const passphrase = "YOUR PASSPHRASE IF THE KEY HAS ONE";
const cred = await Git.Cred.sshKeyMemoryNew(username, publickey, privatekey, passphrase);
const remote = await repository.getRemote("origin");
await remote.push(["refs/head/master:refs/heads/master"], {
callbacks: {
credentials: (url, user) => cred
}
});
You need to run an ssh agent locally and save your password there. Follow these steps to make it work:
Enable the ssh agent locally (automatically runs on OS X): https://code.visualstudio.com/docs/remote/troubleshooting#_setting-up-the-ssh-agent
Run 'ssh-add' in the same CLI as you're running your nodegit actions and enter your passphrase
I hope this helps because I also struggled a lot with it and it can be very frustrating.
I'm trying to create a command, when requested will send a random image from a folder. I don't want to have to name them cause I have a server with a PHP server where my friends can upload images for the bot to post. This is what I have:
if(command === "meme") {
const path = '/img/memes/';
const fs = require('fs');
fs.readdirSync(path).forEach(file => {
ranfile = Math.floor(Math.random()*file.length);
message.channel.sendFile(ranfile);
})
return;
}
When I run the bot with Node.js I get this error:
(node:4840) 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(). (rejection id: 1)
Anyone know what the issue is?
This is probably just a regular error wrapped in an UnhandledPromiseRejectionWarning. Have you tried running with --trace-warnings?
This should solve the problem of getting to the actual issue by providing a reasonable stack trace.