I have a tutorial how to create it,
im on stage he tell me to do something like this "user-registration $export PrivateKey=SecureAF"
what is this mean? what should i do ?
The ERROR at "npm start" is : "FATAL ERROR: PrivateKey is not defined."
index.js :
const config = require('config');
const Joi = require('joi');
Joi.objectId = require('joi-objectid')(Joi);
const mongoose = require('mongoose');
const users = require('./routes/users');
const auth = require('./routes/auth');
const express = require('express');
const app = express();
if (!config.get('PrivateKey')) {
console.error('FATAL ERROR: PrivateKey is not defined.');
process.exit(1);
}
mongoose.connect('mongodb+srv://test:test#cluster0-7n3bu.mongodb.net/test?retryWrites=true&w=majority',
{ useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Now connected to MongoDB!'))
.catch(err => console.error('Something went wrong', err));
app.use(express.json());
app.use('/api/users', users);
app.use('/api/auth', auth);
const port = process.env.PORT || 4000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
Why you are having the error:
The check below in index.js is what leads to the error:
if (!config.get('PrivateKey')) {
console.error('FATAL ERROR: PrivateKey is not defined.');
process.exit(1);
}
config.get('PrivateKey') is supposed to get the value of PrivateKey in your config, however, it seems that value is not present, consequently, the app exits with the error log.
The fix:
I'm guessing you have a config folder in the root of your application, yes? If yes, check your ./config/default.json or ./config/development.json and confirm that there is a PrivateKey config property with a valid value.
Related
I am deploying the server part of a project, built in node and express and it says that the server is live but it doesn't work. In console I get the errors:
" Failed to load resource: the server responded with a status of 404 ()",
" Refused to load the stylesheet 'https://fonts.googleapis.com/css?family=Lato:300,400,700,900' because it violates the following Content Security Policy directive: "default-src 'none'". Note that "style-src-elem" was not explicitly set, so 'default-src' is used as a fallback.".
I don't understand why it gives me that error, since there is no css or html file...
here is my entry js file:
const express = require('express')
const app = express()
const mongoose = require('mongoose')
const xss = require('xss-clean')
const mongoSanitize = require('express-mongo-sanitize')
const { handleError, convertToApiError } = require('./middleware/apiError')
const routes = require('./routes')
const passport = require('passport')
const { jwtStrategy } = require('./middleware/passport')
require('dotenv').config()
const mongoUri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}#${process.env.DB_HOST}? retryWrites=true&w=majority`
mongoose
.set("strictQuery", false)
.connect(mongoUri, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then((x) => {
console.log(
`Connected to Mongo! Database name: "${x.connections[0].name}"`
)
})
.catch((err) => {
console.error("Error connecting to Mongo: ", err)
})
//// body parse
app.use(express.json())
//// sanitize
app.use(xss())
app.use(mongoSanitize())
//// passport
app.use(passport.initialize())
passport.use('jwt', jwtStrategy)
//// routes
app.use('/api', routes)
//// handle errors
app.use(convertToApiError)
app.use((err, req, res, next) => {
handleError(err, res)
})
const port = process.env.PORT || 5005
app.listen(port, () => {
console.log(`Server is running on port ${port}`)
})
I don't even know what I could do...
I deployed my API to Heroku and when I try to use it (login). I get some errors.
my code -
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const cors = require("cors");
// IMPORT FILES
const user = require("./routes/user");
// MONGOOSE CONNECTION
mongoose.connect(
"CONNECTION URL HERE",
{ useNewUrlParser: true },
() => {
console.log("Connected to DB");
}
);
// MIDDLEWARE CONFIGS
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
mongoose.Promise = global.Promise;
// ROUTES REDIRECTION
app.use("/", user);
// SERVER
const server = app.listen(process.env.PORT || 8080, () => {
const port = server.address().port;
console.log(`Server is running on port ${port}`);
});
JWT FILE
const jwt = require("jsonwebtoken");
module.exports = function (req, res, next) {
const token = req.header("token");
if (!token) return res.status(401).send("please login again");
try {
const verify = jwt.verify(token, "JWT SECRET HERE");
req.user = verify;
next();
} catch (err) {
res.status(400).send("invalid token");
}
};
Some pictures of errors-
Error in Heroku logs --tails
error is browser
PS: i had .env for the variables but took 'em out for delpoyment's sake as I was getting Application error.
thank you! help is appreciated.
Have you added your environment variables to heroku config vars?
If not then follow the heroku documentation to do so.
https://devcenter.heroku.com/articles/config-vars
You can use the heroku cli or use the heroku dashboard to add the variables. Refer the docs for a detailed explanation.
Hi in my express project, I have my index file where I require different files to startup my application. These require a database connection file, a file for logging stuff using winston and a file for configuring routes.
I use the require() statement within express to call these files, and when I run the application(using nodemon), I expect some messages to be logged to the terminal verifying that the files have been called, however no messages occur.
Here is my code:
index.js:
const express = require('express')
const app = express()
require('./startup/logging') ()
require('./startup/db') ()
require('./startup/routes') (app)
const port = process.env.PORT || 3000
app.listen(port, () => winston.info(`Listening on port: ${port}`))
db.js:
const mongoose = require('mongoose')
const winston = require('winston')
module.exports = function() {
mongoose.connect('mongodb://localhost/dwg', {useNewUrlParser: true, useUnifiedTopology: true})
.then(() => winston.info('Connected to MongoDB...'))
.catch(err => console.error("Error"))
}
logging.js:
const winston = require('winston');
module.exports = function() {
winston.handleExceptions(
new winston.transports.File({ filename: 'uncaughtExceptions.log' }));
process.on('unhandledRejection', (ex) => {
throw ex;
});
winston.add(winston.transports.File, { filename: 'logfile.log' });
}
routes.js:
const express = require('express');
module.exports = function(app) {
app.use(express.json())
}
No database is created when running the application. I can confirm this by looking at mongodb compass. The message that is meant to be printed by app.listen() is also not printed to the console. Does anybody know the issue? Thank you.
The problem doing it this way is your app starts before it gets a chance to do rest of work like creating db connection etc. You should start the app only when these tasks are done. something like this
const express = require('express')
const app = express()
const logging = require('./startup/logging');
const db = require('./startup/db');
const routes = require('./startup/routes');
const port = process.env.PORT || 3000
app.listen(port, async () => {
await logging();
await db();
await routes();
// assuming you have winston here.
winston.info(`Listening on port: ${port}`)
})
Mongo part is defintely async so need await. Check if routes and logging needs await or not.
I am trying to conceal my connection string, so I installed env2 in my project. Then I made a config.env file that keeps my connection string like this:
export DB_URL='mongodb://user:userPassword#ds241968.mlab.com:41968/heroku_hc9xjmcl'
However when I use that variable as a connection string I cannot connect to Mlab I get the following error:
UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [ds241968.mlab.com:41968] on first connect [MongoError: Authentication failed.]
But when I try to connect only with the string without using env2 I connect perfectly, so why does the ahuthentication fail when I use a env variable and how can I connect with one properly? Here is my server.js:
// Requiring the dependencies
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const PORT = process.env.PORT || 3009;
const itemRoutes = express.Router();
let Comment = require('./comment.model');
const env = require('env2')('../config.env');
console.log(process.env.DB_URL)
app.use(cors());
app.use(bodyParser.json());
const { DB_URL } = process.env;
mongoose.connect( DB_URL , { useNewUrlParser: true } )
const connection = mongoose.connection;
connection.once('open', function() {
console.log('Connection to MongoDB established succesfully!');
});
// Serve static assets
if(process.env.NODE_ENV === 'production') {
app.use(express.static('build'));
}
itemRoutes.route('/').get( async (req, res) => {
let collection = connection.collection("posts");
let response = await collection.find({})
.toArray();
res.send(response);
});
itemRoutes.route('/comments').get( async (req, res) => {
let collection = connection.collection("comments");
let response = await collection.find({})
.toArray();
res.send(response);
});
itemRoutes.route('/userComments')
.post((req, res) => {
res.setHeader('Content-Type', 'application/json');
let comment = new Comment(req.body);
comment.save()
.then(comment => {
res.status(200).json({comment})
})
.catch(err => {
res.status(400).send('failed')
})
});
app.use('/', itemRoutes);
app.use('/userComments', itemRoutes);
app.listen(PORT, function() {
console.log('Server is running on' + ' ' + PORT);
})
Looks like you are using Node and Heroku. In that case,
You should set Heroku Config Vars (you can do this either via CLI or your Heroku Dashboard)
Refer to the config var in your node application the same way you are referring to now.
Remove 'env2' related code as you won't need it for this purpose
For example, if you create Heroku config var called "MONGO_URI", refer to it as process.env.MONGO_URI in your node application.
Details can be found here: https://devcenter.heroku.com/articles/config-vars#managing-config-vars
I'm trying to retrieve data from my mongo database. The problem occurs when I try to do the get route in my API. The error I get is: SchemeName.collection is not a function.
Here is my API in routes/api/tejidos
const express = require("express");
const router = express.Router();
const Equipo = require("../../../models/Equipo");
router.post("/crear", (req, res) => {
// Form validation
const newEquipo = new Equipo({
nombre: req.body.nombre,
marca: req.body.marca,
modelo: req.body.modelo,
serial: req.body.serial,
proveedor: req.body.proveedor,
estado: req.body.estado,
zona: req.body.zona,
fechaCompra: req.body.fechaCompra,
tiempoGarantia: req.body.tiempoGarantia,
guiaUsoRapido:req.body.guiaUsoRapido
});
//if (err) throw err
newEquipo
.save()
.then(equipo=>res.json(equipo))
.catch(err => console.log(err));
});
router.get('/leer', function(req, res) {
const equipos = Equipo.collection("equipos")
res.json({
equipos: equipos
});
});
module.exports = router;
And this is my server.js
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const users = require("./routes/api/users");
const equipos = require("./routes/api/tejidos/equipos");
const app = express();
// Bodyparser middleware
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
// DB Config
const db = require("./config/keys").mongoURI;
// Connect to MongoDB
mongoose
.connect(
db,
{ useNewUrlParser: true }
)
.then(() => console.log("MongoDB successfully connected"))
.catch(err => console.log(err));
// Passport middleware
app.use(passport.initialize());
// Passport config
require("./config/passport")(passport);
// Routes
app.use("/api/users", users);
app.use("/api/tejidos/equipos", equipos);
const port = process.env.PORT || 5000; // process.env.port is Heroku's port if you choose to deploy the app there
app.listen(port, () => console.log(`Server up and running... ${port} !`));
I need to retrieve data in my collection (the ones I created with the post method) from the database when I use the GET method in Postman at http://localhost:5000/api/tejidos/equipos/leer
Also, I will appreciate any documentation that you recommend.
Simply use find method:
router.get('/leer', async (req, res) => {
const equipos = await Equipo.find();
res.json({ equipos });
});
And here is the helpful documentation for making queries with mongoose