I have created a react app, and I have connected the mongoDB database, now the problem is whenever I start the node server the server gets started as well as the mongodb database, but most of the time the mongoDB database shows timeout error.
I am adding image, have a look through it for the error as well as I am showing my pacakage.json file.
{
"name": "ewk",
"version": "1.0.0",
"description": "abcd",
"main": "server.js",
"type": "module",
"scripts": {
"start": "node backend/server",
"server": "nodemon backend/server",
"client": "npm start --prefix frontend",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"data:import": "node backend/seeder",
"data:destroy": "node backend/seeder -d"
},
"author": "xyz",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-async-handler": "^1.1.4",
"mongoose": "^5.11.13"
},
"devDependencies": {
"concurrently": "^5.3.0",
"nodemon": "^2.0.7"
}
}
This is my database configuration code:
import mongoose from 'mongoose';
const connectDB = async () => {
try{
const conn = await mongoose.connect(process.env.MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true
})
console.log(`MongoDB Connected: ${conn.connection.host}`)
} catch (error){
console.error(`Error: ${error.message}`)
process.exit(1)
}
}
export default connectDB
I have added the uri which I added in env file:
mongodb+srv://abj:*******#ewfsa-cluster.hbwdr.mongodb.net/EWFSA?retryWrites=true&w=majority
Related
I am facing
[nodemon] app crashed - waiting for file changes before starting...
While hosting my NodeJS Apollo GraphQL express server on Heroku.
It is also showing
2022-10-06T17:21:11.889722+00:00 app[web.1]: [nodemon] 2.0.20
2022-10-06T17:21:11.889912+00:00 app[web.1]: [nodemon] to restart at any time, enter `rs`
2022-10-06T17:21:11.890274+00:00 app[web.1]: [nodemon] watching path(s): *.*
2022-10-06T17:21:11.890314+00:00 app[web.1]: [nodemon] watching extensions: js,mjs,json
2022-10-06T17:21:11.890669+00:00 app[web.1]: [nodemon] starting `nodemon -r esm .`
2022-10-06T17:21:13.608667+00:00 app[web.1]: /app/node_modules/esm/esm.js:1
2022-10-06T17:21:13.616378+00:00 app[web.1]: const __global__ = this;(function (require, module, __shared__) { var __shared__;const
Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
Here is my index.js
import express from "express";
import mongoose from "mongoose";
import { DB, mode } from "./config";
import { ApolloServer } from "apollo-server-express";
import AuthMiddleware from "./middlewares/auth";
import * as AppModels from "./models";
import { resolvers, typeDefs } from "./graphql";
const startServer = async () => {
const PORT = process.env.PORT || 3000;
try {
const app = express();
app.use(AuthMiddleware);
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
playground: mode,
context: ({ req }) => {
let { isAuth, user } = req;
return { req, isAuth, user, ...AppModels };
},
});
mongoose.connect(DB, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
await apolloServer.start();
await apolloServer.applyMiddleware({ app });
app.listen({ port: PORT }, () =>
console.log(`Server started at port ${PORT}`,)
);
} catch (err) {
console.log("error: "+err);
}
};
startServer();
Here is my package.json
{
"name": "forefest-backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon -r esm .",
"server": "sudo systemctl start mongod && nodemon -r esm",
"dev": "nodemon -r esm"
},
"repository": {
"type": "git",
"url": "git+https://github.com/anshuman-8/forefest-backend.git"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/anshuman-8/forefest-backend/issues"
},
"homepage": "https://github.com/anshuman-8/forefest-backend#readme",
"dependencies": {
"apollo-server-express": "^3.10.2",
"bcryptjs": "^2.4.3",
"consola": "^2.15.3",
"dotenv": "^16.0.2",
"esm": "^3.2.25",
"express": "^4.18.1",
"graphql": "^16.6.0",
"jsonwebtoken": "^8.5.1",
"lodash": "^4.17.21",
"mongoose": "^6.6.1",
"mongoose-paginate-v2": "^1.7.1",
"nodemon": "^2.0.20",
"yup": "^0.32.11"
}
}
I have tried multiple ways of fixing this problem, Please help me.
This is my first time deploying a server.
My project has 2 folders: client(next.js with custom server) and server(node.js).
I have uploaded it in a Ubuntu 20.04 server and build next.js project in client folder. it works.
I have recently changed some pages of next.js and uploaded to client folder by "sudo git pull".
Now I would like to run "npm run build" to build next.js again, but it gives Error:
warn - No ESLint configuration detected. Run next lint to begin setup
Build error occurred
Error: > Build directory is not writeable. https://nextjs.org/docs/messages/build-dir-not-writeable
at /home/skadmin/client/node_modules/next/dist/build/index.js:275:19
at async Span.traceAsyncFn (/home/skadmin/client/node_modules/next/dist/telemetry/trace/trace.js:60:20)
at async Object.build [as default] (/home/skadmin/client/node_modules/next/dist/build/index.js:77:25)
info - Creating an optimized production build
==========My Custom server is:
'''
const express = require('express')
const next = require('next')
const { createProxyMiddleware } = require('http-proxy-middleware')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app
.prepare()
.then(() => {
const server = express()
// apply proxy in dev mode
if (dev) {
server.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:8000',
changeOrigin: true,
})
)
}
server.all('*', (req, res) => {
return handle(req, res)
})
server.listen(3000, (err) => {
if (err) throw err
console.log('> Ready on http://localhost:8000')
})
})
.catch((err) => {
console.log('Error', err)
})
'''
=======================package.json is=>:
'''
{
"name": "client",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"#ant-design/icons": "^4.5.0",
"#glidejs/glide": "^3.4.1",
"#material-ui/core": "^4.11.4",
"#material-ui/icons": "^4.11.2",
"#persian-tools/persian-tools": "^3.0.1",
"antd": "^4.13.1",
"axios": "^0.21.4",
"express": "^4.17.1",
"http-proxy-middleware": "^2.0.0",
"lodash": "^4.17.21",
"moment-jalaali": "^0.9.2",
"multer": "^1.4.4",
"next": "^11.1.3",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-icons": "^4.2.0",
"react-image-file-resizer": "^0.4.7",
"react-markdown": "^6.0.2",
"react-scroll": "^1.8.2",
"react-toastify": "^7.0.4",
"reactstrap": "^8.9.0",
"swiper": "^7.4.1"
}
}
'''
Please help me, what should I do?
I am seeing this error in my index.js file in VSC which looks to be caused by the app.post request.
I've attempted different parsing options in regards to eslint and emca but still aren't getting anywhere.
Appreciate any input.
Parsing error: Unexpected token => eslint
index.js
const functions = require("firebase-functions");
const express = require("express");
const cors = require("cors");
const stripe = require("stripe")("hidden");
// Setting Up the API
// - App Config
const app = express();
// - Middlewares
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 Recieved for this amount >>> ", total);
const paymentIntent = await stripe.paymentIntents.create({
amount: total, // subunits of the currency
currency: "usd",
});
// OK - Created
response.status(201).send({
clientSecret: paymentIntent.client_secret,
});
});
// - Listen command
exports.api = functions.https.onRequest(app);
This is my package.json
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint .",
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "14"
},
"main": "index.js",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.17.1",
"firebase-admin": "^9.8.0",
"firebase-functions": "^3.14.1",
"stripe": "^8.174.0"
},
"devDependencies": {
"#babel/core": "^7.15.5",
"#babel/eslint-parser": "7.15.4",
"eslint": "^7.6.0",
"eslint-config-google": "^0.14.0",
"eslint-plugin-react": "^7.25.1",
"firebase-functions-test": "^0.2.0"
},
"private": true
}
And then this is my .eslintrc.js file
module.exports = {
root: true,
env: {
es6: true,
node: true,
},
extends: [
"eslint: recommended",
"google",
"plugin: react/recommended",
],
rules: {
quotes: ["error", "double"],
},
};
Seems like you're missing parser: #babel/eslint-parser from your eslintrc
I am trying to create a seeder file in nestjs, the problem is when I run the project using start:dev, somehow nestjs also start seed.ts file with main.ts file. How can I make nestjs not start seed file when I run the project either on prod/dev but seed must be called only when I run the seed script.
Here is the seed.ts code
import { NestFactory } from '#nestjs/core'
import { Logger } from '#nestjs/common'
import { SeederModule } from './database/seeder.module'
import { Seeder } from './database/seeder'
async function bootstrap() {
NestFactory.createApplicationContext(SeederModule)
.then((appContext) => {
const logger = appContext.get(Logger)
const seeder = appContext.get(Seeder)
seeder
.seedRoles()
.then(() => {
logger.debug('Seeding Roles complete!')
})
.catch((error) => {
logger.error('Seeding Roles failed!')
throw error
})
seeder
.seedAdmin()
.then(() => {
logger.debug('Seeding Admin complete!')
})
.catch((error) => {
logger.error('Seeding Admin failed!')
throw error
})
.finally(() => appContext.close())
})
.catch((error) => {
throw error
})
}
bootstrap()
Here is the main.ts file for nestJS
import { Logger, ValidationPipe } from '#nestjs/common'
import { NestFactory } from '#nestjs/core'
import { AppModule } from './modules/app/app.module'
async function bootstrap() {
const app = await NestFactory.create(AppModule)
app.enableCors()
const port = process.env.PORT || 3000
app.useGlobalPipes(new ValidationPipe())
await app
.listen(port)
.then(() => {
Logger.log(`App listening on port ${port}`)
})
.catch((err) => {
Logger.log(`Error while connecting to port ${port}`, err)
})
}
bootstrap()
And here is the package.json file
{
"name": "jugg-website",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "link-module-alias && nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json",
"seed": "ts-node -r tsconfig-paths/register src/seed.ts"
},
"dependencies": {
"#nestjs/common": "^7.6.13",
"#nestjs/core": "^7.6.13",
"#nestjs/jwt": "^7.2.0",
"#nestjs/passport": "^7.1.5",
"#nestjs/platform-express": "^7.6.13",
"#nestjs/typeorm": "^7.1.5",
"class-transformer": "^0.4.0",
"class-validator": "^0.13.1",
"config": "^3.3.6",
"link-module-alias": "^1.2.0",
"passport": "^0.4.1",
"pg": "^8.5.1",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^6.6.6",
"typeorm": "^0.2.32"
},
"devDependencies": {
"#nestjs/cli": "^7.5.6",
"#nestjs/schematics": "^7.2.7",
"#nestjs/testing": "^7.6.13",
"#types/express": "^4.17.11",
"#types/jest": "^26.0.20",
"#types/node": "^14.14.31",
"#types/supertest": "^2.0.10",
"#typescript-eslint/eslint-plugin": "^4.15.2",
"#typescript-eslint/parser": "^4.15.2",
"eslint": "^7.20.0",
"eslint-config-prettier": "^8.1.0",
"eslint-plugin-prettier": "^3.3.1",
"jest": "^26.6.3",
"prettier": "^2.2.1",
"supertest": "^6.1.3",
"ts-jest": "^26.5.2",
"ts-loader": "^8.0.17",
"ts-node": "^9.1.1",
"tsconfig-paths": "^3.9.0",
"typescript": "^4.1.5"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
you can try setting KeepConnectionAlive option to true in typeOrm
configuration in the app.module file
https://github.com/nestjs/typeorm/issues/61
I was getting this error when running e2e tests. I found that the default nestjs template sets up the e2e tests with a beforeEach like this:
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
But since I had more than one test in the spec file (I'm a newbie to node.js dev so not sure whether this is the right thing to do or not, but regardless...), what was happening was the app was being initialised once per test which meant it was attempting to create multiple connections to the database.
The solution was quite simple. Change the beforeEach to beforeAll
beforeAll(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
And don't forget to close the app when the tests are done
afterAll(async () => {
await app.close();
});
In my case, the problem was in my main.ts file. I ran my module with the TypeORM twice without noticing, because I was trying access my ConfigService so that I could use environment variables for some other service than my TypeORM database connection.
main.ts that causes the error:
...
async function bootstrap(): Promise<void> {
// the next line actually initiates a DB connection
const appContext = await NestFactory.createApplicationContext(MailModule);
const configService = appContext.get<ConfigService>(ConfigService);
// by now, we already established a DB connection, so trying to
// reinstantiate the connection will cause the error
const app = await NestFactory.createMicroservice<MicroserviceOptions>(
MailModule,
{
transport: Transport.REDIS,
options: {
port: configService.get<number>('REDIS.PORT'),
host: configService.get<string>('REDIS.HOST'),
},
},
);
await app.listen();
}
bootstrap();
The solution:
...
async function bootstrap(): Promise<void> {
const appContext = await NestFactory.createApplicationContext(MailModule);
// we close the redundant connection before we mount the app.
await getConnection('default').close();
const configService = appContext.get<ConfigService>(ConfigService);
const app = await NestFactory.createMicroservice<MicroserviceOptions>(
MailModule,
{
transport: Transport.REDIS,
options: {
port: configService.get<number>('REDIS.PORT'),
host: configService.get<string>('REDIS.HOST'),
},
},
);
await app.listen();
}
bootstrap();
I have the following webhook, and it is listening for a payment provider API to update the status of an order once it is 'paid'. In logs for Firebase Functions, I get the console log Payment status paid meaning that I get the update of the order correctly. However, when I try to call the function responsible for updating Firestore, I get the following:
#firebase/firestore: Firestore (7.16.0): Connection GRPC stream error. Code: 13 Message: 13 INTERNAL: Received RST_STREAM with code 2
exports.webhooks = functions.https.onRequest(function (req, res) {
mollieClient.payments
.get(req.body.id)
.then((payment) => {
console.log("Payment status " + payment.status);
if (payment.isPaid()) {
updateOrderStatusPaid(req.body.id);
return null;
}
return null;
})
.catch((error) => {
res.send(error);
});
console.log("Request body " + req.body);
});
function updateOrderStatusPaid(orderId) {
firebase
.firestore()
.collection("orders")
.where("paymentId", "==", orderId)
.update({
status: payment.status
})
.then(function () {
console.log("Success");
return null;
})
.catch(function (error) {
console.log("Error " + error);
});
}
Here is my package.json file
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint .",
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "8"
},
"dependencies": {
"#mollie/api-client": "^3.2.4",
"axios": "^0.20.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"firebase": "^7.16.0",
"firebase-admin": "^8.10.0",
"firebase-functions": "^3.6.1",
"grpc": "^1.24.4"
},
"devDependencies": {
"eslint": "^5.12.0",
"eslint-plugin-promise": "^4.0.1",
"firebase-functions-test": "^0.2.0"
},
"private": true
}
I cannot find anything specific to this problem. I am already using Firestore on my server side so there is no problem with initialization of Firebase. Maybe somebody knows where the problem might be or suggest something I should do to solve this. Thank you!
The closest link to this problem is https://github.com/googleapis/nodejs-datastore/issues/679 where still there is not answer.