Why am I receiving the error: "Missing script: Start"? - node.js

I'm trying to follow a tutorial for starting up my first NodeJS app, but I don't understand why I am getting this error. I'm attempting to connect a MongoDB database with the app, and obviously had to modify my Start.js file in order to do that... but the error says I'm missing that file completely. Here's my Start.js:
require('dotenv').config();
const mongoose = require('mongoose');
mongoose.connect(process.env.DATABASE, { useMongoClient: true });
mongoose.Promise = global.Promise;
mongoose.connection
.on('connected', () => {
console.log(`Mongoose connection open on ${process.env.DATABASE}`);
})
.on('error', (err) => {
console.log(`Connection error: ${err.message}`);
});
const app = require('./app');
const server = app.listen(3000, () => {
console.log(`Express is running on port ${server.address().port}`);
});
I was told to create a .env file to place in the project folder as well, could this have something to do with it? Maybe the address to the database is incorrect? Any assistance would be greatly appreciated.
EDIT: Here's my package.json file
{
"name": "demo-node-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"watch": "nodemon ./start.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-validator": "^6.3.0",
"mongoose": "^5.8.3",
"pug": "^2.0.4"
},
"devDependencies": {
"nodemon": "^2.0.2"
}
}

Related

Can not Find module in "index.js"

I'm stuck in this error...I'm trying but I can not fix it
This is my index.js file
import express from "express";
import dotenv from "dotenv";
import mongoose from "mongoose";
const app = express();
dotenv.config();
const connect = async () => {
try {
await mongoose.connect(process.env.MONGO);
console.log("Connected to mongoDB.");
} catch (error) {
throw error;
}
};
mongoose.connection.on("disconnected", () => {
console.log("mongoDB disconnected!");
});
app.listen(3000, () => {
connect();
console.log("Connected to backend.");
});
This is my pacakge.json file
{
"name": "quiz-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"dotenv": "^16.0.2",
"express": "^4.18.1",
"mongoose": "^6.5.4"
},
"devDependencies": {
"webpack-cli": "^3.3.12"
}
}
when I run this app it shows this error
enter image description here
You are using ES6 style importing import express from "express"; but your package.json doesn't know about that. Because the default is CommonJS for Node.js right now. And that means it wants you to use const express = require("express");
If you want to change that to ES6, you need to add "type": "module", in your package.json.
For example:
...
"description": "",
"type": "module",
"main": "index.js",
...

Can't connect pgadmin to the server

I'm trying to connect my server (based on node.js) with db from pgAdmin.<>
However I keep getting '${PORT}', instead of PORT's value in env file :
pgAdmin part:
index.js file:
require('dotenv').config()
const express = require ('express')
const sequelize = require('./db')
const PORT = process.env.PORT || 5000
const app = express()
const start = async () => {
try {
await sequelize.authenticate()
await sequelize.sync()
app.listen(PORT,()=>console.log('Server started on port ${PORT}'))
} catch (e) {
console.log(e)
}
}
start()
db.js:
const {Sequelize} = require('sequelize')
module.exports = new Sequelize(
process.env.DB_NAME,
process.env.DB_USER,
process.env.DB_PASSWORD,
{
dialect:'postgres',
host: process.env.DB_HOST,
port: process.env.DB_PORT
}
)
.env file:
PORT=7000
DB_NAME=postgres
DB_USER=postgres
DB_PASSWORD='Ondj8_oP1sw'
DB_HOST=localhost
DB_PORT=5432
package.json:
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.0.1",
"express": "^4.18.1",
"pg": "^8.8.0",
"pg-hstore": "^2.3.4",
"sequelize": "^6.21.4"
},
"devDependencies": {
"nodemon": "^2.0.19"
}
}
The actual connection should be fine, yet your console.log should look like console.log(`Server started on port ${PORT}`), use back ticks `` if you want to console.log a variable.

NODE API runs on localhost but doesn't run on Vercel

I'm trying to upload a node app to Vercel and use as API but I'm getting an This Serverless Function has crashed. error message. The fact that I can run it with no problems in localhost, and the fact that the build log doesn't throw an error, I can't seems to find the problem.
Here is a full Screenshot:
vercel app
And here is my index.js:
const express = require(`express`);
var cors = require('cors')
const app = express();
app.use(cors())
const bodyParser = require('body-parser')
const mongoose = require("mongoose")
require("dotenv").config();
const config = require('config');
const dbConfig = config.get("MT.dbConfig.dbName")
mongoose.connect(dbConfig, {
}).then(() => {
console.log('Database connected.')
}).catch((err)=> console.log('Something went wrong with the database : ' + err))
mongoose.Promise = global.Promise;
app.use(bodyParser.json())
app.use('/', require('./api/v1/api'))
app.use((err, req, res, next) =>{
res.status(422).send({
error: err._message
})
})
const PORT = 5001;
app.listen(PORT, () => console.log("API is running."))
And here is my package.json:
{
"name": "hidden",
"version": "1.0.0",
"description": "",
"main": "index.js",
"engines": {
"node": "14.x"
},
"scripts": {
"start": "vercel dev",
"deploy": "vercel deploy --prod"
},
"author": "hidden",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"config": "^3.3.6",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"mongoose": "^6.0.13",
"vercel": "^23.1.2"
},
"devDependencies": {
"nodemon": "^2.0.15"
}
}

getting the warning [current Server Discovery and Monitoring engine is deprecated] after using winston-mongodb

after installing winston-mongodb I got the following warning :
(node:9316) DeprecationWarning: current Server Discovery and
Monitoring engine is deprecated, and will be removed in a future
version. To use the new Server Discover and Monitoring engine, pass
option { useUnifiedTopology: true } to the MongoClient constructor.
this is my app.js :
require('express-async-errors');
const express = require('express'),
config = require('config'),
morgan = require('morgan'),
helmet = require('helmet'),
winston = require('winston'),
mongoose = require('mongoose');
require('winston-mongodb');
mongoose.connect("mongodb://localhost:27017/wsep",
{ useNewUrlParser: true, useFindAndModify: false, useCreateIndex: true, useUnifiedTopology: true })
.then(connect => { console.log("connected to mongo db...") })
.catch(error => { console.log("could not connect to mongo db ...") })
winston.add(new winston.transports.MongoDB({
db: 'mongodb://localhost:27017/wsep'
}));
the warning above will be disappeared , if I remove/comment the following snippet code:
winston.add(new winston.transports.MongoDB({
db: 'mongodb://localhost:27017/wsep'
}));
EDIT:
package.json
{
"name": "backend-api",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "nodemon app.js",
"start": "node app.js"
},
"engines": {
"node": "13.5.0"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt-nodejs": "0.0.3",
"compression": "^1.7.4",
"config": "^3.2.5",
"express": "^4.17.1",
"express-async-errors": "^3.1.1",
"helmet": "^3.21.2",
"joi": "^14.3.1",
"jsonwebtoken": "^8.5.1",
"jwt-token-encrypt": "^1.0.4",
"lodash": "^4.17.15",
"mongoose": "^5.8.9",
"multer": "^1.4.2",
"winston": "^3.2.1",
"winston-mongodb": "^5.0.1"
},
"devDependencies": {
"nodemon": "^2.0.2"
}
}
You can just add useUnifiedTopology: true to the options block of winston-mongodb
like this:
winston.add(new winston.transports.MongoDB({
db: 'mongodb://localhost:27017/wsep',
options: {
useUnifiedTopology: true,
}
}));
Passing useUnifiedTopology:true to options worked for me. See the xample below:
// Connect to Mongo
mongoose.set("useNewUrlParser", true);
mongoose.set("useUnifiedTopology", true);
mongoose
.connect(db)
.then(() => console.log("MongoDB Connected..."))
.catch(() => console.log(err));

Node.js app crashing with an R10 error

I am trying to successfully deploy a Node/React project on Heroku and after hours of debugging issues (I am a new developer) I think I got it near the finish line but now Heroku is posing some issues with deployment.
For background, here is my package.json file so you know what I have installed:
{
"name": "StarterApp",
"version": "1.0.0",
"engines": {
"node": "10.4.1",
"npm": "6.1.0"
},
"description": "",
"main": "index.js",
"scripts": {
"test": "mocha",
"dev": "node server.js",
"build": "next build"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "4.16.3",
"fs-extra": "^5.0.0",
"ganache-cli": "^6.1.3",
"mocha": "^5.2.0",
"next": "^4.2.3",
"next-routes": "^1.4.2",
"node-gyp": "^3.7.0",
"react": "^16.4.1",
"react-dom": "^16.4.1",
"rebuild": "^0.1.2",
"semantic-ui-css": "^2.3.2",
"semantic-ui-react": "^0.79.1",
"sha3": "^1.2.2",
"solc": "^0.4.24",
"truffle-hdwallet-provider": "0.0.3",
"web3": "^1.0.0-beta.34"
}
}
This is what I have in my server.js file:
app.prepare().then(() => {
createServer(handler).listen(5000, (err) => {
if (err) throw err;
console.log('Ready on localhost:5000');
});
This is what Heroku suggests the code to look like (source):
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(Our app is running on port ${ PORT });
});
The problem I am running into is that I am not sure how to merge what I already have with what Heroku wants me to use. My code is necessary so that it works with NextJS and the Heroku code is agnostic of that. What can I do to make the two work together? Thanks!
I figured it out it seems. I just did the following:
app.prepare().then(() => {
const PORT = process.env.PORT || 3000;
createServer(handler).listen(PORT, (err) => {
if (err) throw err;
console.log('Ready on localhost:5000');
});
Doing that allowed me to use both NextJS and Heroku suggested code.

Resources