I am getting this error when trying to run my code and don't really know how to solve it. I don't really know the codebase because I'm new to it, so I'm completely lost and have no idea what to do.
body-parser deprecated undefined extended: provide extended option index.js:20:20
COMMON_CONFIG.mode === "development" false
Listening on port undefined
edit:
package.json:
**{
"name": "audio-guide-backend",
"version": "0.0.0",
"main": "index.js",
"repository": "https://gitlab.com/islandica/audio-guide-backend.git",
"license": "MIT",
"private": true,
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
},
"dependencies": {
"crypto-random-string": "^3.0.1",
"dotenv": "^8.0.0",
"ejs": "^2.6.2",
"express": "^4.17.1",
"express-session": "^1.16.2",
"pg": "^7.11.0"
},
"devDependencies": {
"nodemon": "^1.19.1"
}
}
**
Edit 2: This is how my index.js looks like:
require("dotenv").config();
const express = require("express");
const http = require("http");
const session = require("express-session");
const bodyParser = require("body-parser");
const { SERVER_CONFIG } = require("./config");
const app = express();
const server = http.createServer(app);
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use((req, res, next) => {
// if (req.url === "/api/login") console.log(req);
next();
});
app.use(express.json());
app.use(bodyParser.urlencoded());
app.use(
session({
secret: "keyboard cat",
resave: false,
saveUninitialized: true
})
);
// ROUTES
require("./routes")(app);
// NOT FOUND
app.use(function(req, res, next) {
res.status(404);
res.format({
html: function() {
res.render("404");
// res.render("404", { url: req.url });
},
json: function() {
res.json({ message: "Not found" });
},
default: function() {
res.type("txt").send("Not found");
}
});
});
// INTERNAL ERROR
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.format({
html: function() {
res.render("500");
},
json: function() {
res.json({ message: "server error: " + err.message });
},
default: function() {
res.type("txt").send("server error: " + err.message);
}
});
res.send("server error: " + err.message);
/*res.render("500", {
message:
COMMON_CONFIG.mode === "development"
? err.message
: "Internal server error"
});*/
});
server.listen(SERVER_CONFIG.port, err => {
if (err) {
console.log("Error occured");
} else {
console.log(`Listening on port ${SERVER_CONFIG.port}`);
}
});
It looks like my post is mostly code, so I'm adding more details.
Listening on port undefined
This means that you don't have the port set. I see you're using dotenv, so the first place to check is your .env file in the root directory. If one wasn't created, make it and add whatever the name is for the environmental variable referenced in index.js. It's likely PORT.
Next you'll want to review the options you're passing into express.json() or whatever body-parser function you're calling. It's passing an undefined into that also.
Check your .env file or your system environmental variables and add the ones needed.
EDIT:
Check SERVER_CONFIG in the config file. That's where you should have you environmental variables that would usually be in .env. It's possible and likely that SERVER_CONFIG just consumes the dotenv package.
Also, you do not need const server = http.createServer(app); Just replace the call to server.listen(...) with app.listen(...)
Remove bodyParser, and use express.urlencoded({extended: true})
Since the bodyParser is deprecated, I had resolved this issue by setting the extended:true option on the app.
app.use(express.urlencoded({extended: true}));
instead of
app.use(bodyParser.urlencoded());
Related
I am trying to deploy my app to Heroku. I am getting 503 (Service Unavailable) error even though it runs on localhost. I have tried many solutions, but none of them are working. My app.js file
if (process.env.NODE_ENV !== "production") {
require("dotenv").config();
}
const express = require("express");
const mongoose = require("mongoose");
const { ApolloServer } = require("apollo-server-express");
const auth = require("./middleware/auth");
const userController = require("./controllers/userController");
const typeDefs = require("./schema");
const resolvers = require("./resolvers");
const port = process.env.PORT || 4000;
const app = express();
app.set("port", port);
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Methods",
"OPTIONS, GET, POST, PUT, PATCH, DELETE"
);
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
next();
});
app.use(auth);
app.get("/email-confirmation/:token", userController.confirmationPost);
const server = new ApolloServer({
typeDefs,
resolvers,
formatError: (err) => {
if (!err.originalError) {
return err;
}
if (err.message.startsWith("Database Error: ")) {
err.message = "Internal server error";
}
const data = err.originalError.data;
const message = err.message || "Internal server error.";
const code = err.originalError.code || 500;
return { message: message, status: code, data: data };
},
context: ({ req, res }) => ({
req,
res,
}),
});
server.applyMiddleware({ app });
mongoose
.connect(process.env.DB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
})
.then(() => {
console.log("conneted to database");
app.listen(port, () => {
console.log("listening for requests on port " + port);
});
});
And my package.json is:
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js",
"dev": "nodemon app.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"apollo-server-express": "^2.17.0",
"bcryptjs": "^2.4.3",
"crypto": "^1.0.1",
"express": "^4.17.1",
"graphql": "^15.3.0",
"jsonwebtoken": "^8.3.0",
"mongoose": "^5.10.2",
"nodemailer": "^6.4.16",
"nodemailer-sendgrid-transport": "^0.2.0",
"validator": "^10.8.0"
},
"devDependencies": {
"dotenv": "^8.2.0",
"eslint": "^7.7.0",
"nodemon": "^2.0.6"
}
}
heroku logs --tail command gives following output:
I have tried every solution. But none of them seems to resolve the issue. Please, help.
UPDATE:
After I setup DB_URL in Heroku, it started working but I am getting another error.
Console:
1. GET https://capstone-ecommerce-backend.herokuapp.com/ 404 (Not Found)
2. Refused to load the image 'https://capstone-ecommerce-backend.herokuapp.com/favicon.ico' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'img-src' was not explicitly set, so 'default-src' is used as a fallback.
Try setting up the DB_URL in your Heroku application. Use the following command:
$ heroku config:set DB_URL=database_uri_here
I have been working with another developer and we have been able to deploy the React + Node.js application using Express to Heroku, however we are still receiving an error as shown below in the screenshot.
I am apparently getting a 404 from the server and I feel that we are close to resolving the problem; we just do not know if it is a simple syntax fix or structure in general.
Here is my root package.json file:
{
"name": "dev-personal-portfolio-2",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start": "node server.js",
"server": "nodemon index.js",
"test": "echo \"Error: no test specified \" && exit 1",
"post-build": "cd client && npm i && npm run build"
},
"author": "",
"license": "ISC",
"dependencies": {
"#sendgrid/mail": "^7.2.1",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"nodemon": "^2.0.4"
}
}
Here is the server.js file:
require ('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
const buildPath = ('build/index.html');
const port = process.env.PORT || 5000;
const sendGrid = require('#sendgrid/mail');
const server = express();
server.use(bodyParser.json());
server.use(cors());
// server.use((req, res, next) => {
// res.setHeader('Access-Control-Allow-Origin', '*');
// res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE');
// res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
// next();
// });
// server.get('/api', (req, res, next) => {
// res.send('API Status: Running')
// });
server.use(express.static('client/build'));
// server.use('/static', express.static('public'))
// server.use(express.static(path.resolve(__dirname, './public')));
// server.get('*', (req, res) => {
// res.sendFile(path.resolve(__dirname, 'index.html'));
// });
console.log(express.static('client/build'));
console.log(`${__dirname}/public/index.html`);
server.use(express.json());
const REACT_APP_SENDGRID_API_KEY =`${process.env.REACT_APP_SENDGRID_API_KEY}`
server.post('/api/email', (req, res, next) => {
sendGrid.setApiKey(REACT_APP_SENDGRID_API_KEY);
console.log(req.body);
const msg = {
to: 'kevgill95#gmail.com',
from: req.body.email,
subject: req.body.subject,
text: req.body.message
}
sendGrid.send(msg)
.then(result => {
res.status(200).json({
success: true
});
})
.catch(err => {
console.log('error: ', err);
res.status(401).json({
success: false
})
})
});
server.listen(port, () => {
console.log(`Server is up on port ${port}!`);
});
NOTE: for the console.logs, here is what is returning from them:
console.log(express.static('client/build'));
[Function: serveStatic]
console.log(${__dirname}/public/index.html);
/Users/kevingillooly/dev-personal-portfolio-2/public/index.html
We have tried commenting out lines of code as well to try to resolve the problem, but we have not encountered anything that works.
If anyone would know what the problem would be, that would be awesome. The build succeeds just fine however the problem is very vague and we have tried a lot of different methods.
I am attempting to learn express and how to use postman and I'm following along a tutorial. Everything was going well until I tested router.get by sending dummy data to the server. I use postman to attempt to post to my localhost 500. Instead of getting a json back of the data in which I sent, I get a 200 status and nothing at the bottom of my screen. When i check the console upon hitting that route, this is logged to the console: http://undefined/api/members.
Mind you, I have no trouble using router.get to receive a json of all my members and I have no trouble receiving a json by searching with just the member ID. But for whatever reason router.post isn't working for me. I suspect this has to do with the body parser. But I'm not sure why specifically it isn't working. Please help.
This is how I set up my app file:
const express = require('express')
const app = express()
const path = require('path');
const logger = require('./middleware/logger')
const bodyParser = require('body-parser')
app.use(logger)
app.use('/api/members', require('./routes/api/members'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))
app.use(express.static(path.join(__dirname, 'public')))
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log(`Server started on port ${[PORT]}`)
})
The following is how I set up my router file
const express = require('express')
const router = express.Router()
const members = require('../../Members')
router.get('/', (req, res) =>{
res.json(members);
})
router.get('/:id', (req, res) => {
const found = members.some(member => member.id === parseInt(req.params.id));
if(found){
res.json(members.filter(member => member.id === parseInt(req.params.id)))
} else {
res.status(400).json({msg: `No member with the id of ${req.params.id}`})
}
})
router.post('/', (req, res) => {
res.send(req.body)
})
module.exports = router
my package.json:
{
"name": "expressCrashCourse",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index",
"dev": "nodemon index"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"moment": "^2.24.0"
},
"devDependencies": {
"nodemon": "^2.0.2"
}
}
Routes are processed in order so if you want the body-parser middleware to be active for your .post() route, the middleware has to be BEFORE it. So, change this:
app.use('/api/members', require('./routes/api/members'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))
to this:
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))
app.use('/api/members', require('./routes/api/members')) // <== after your middleware
As it was, it was hitting your route before the middleware got a chance to run and thus req.body was still not populated with the body contents.
I am trying to create a Swagger spec and application for my express api. My app.js file is:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var tenants = require('./routes/tenants');
var models = require('./models.js');
var resources = require('./resources.js')
var app = express();
var swagger = require('swagger-node-express').createNew(app);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
swagger.addModels(models);
swagger.addGet(resources.getTenantById);//This is where I am getting the error
swagger.setApiInfo({
title: "Swagger Sample App",
description: "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.wordnik.com or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters",
termsOfServiceUrl: "http://helloreverb.com/terms/",
contact: "apiteam#wordnik.com",
license: "Apache 2.0",
licenseUrl: "http://www.apache.org/licenses/LICENSE-2.0.html"
});
swagger.configureSwaggerPaths("", "api-docs", "")
swagger.configure("http://localhost:8002", "1.2.0");
app.use('/', routes);
app.use('/users', users);
app.use('/tenants',tenants);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.listen(8002);
My resources.js file is :
var sw = require('./node_modules/swagger-node-express/Common/node');
var swe = sw.swagger.errors;
var params = sw.paramTypes;
var url = require('url');
exports.getTenantById = {
'spec' : {
description : "Operations on Tenants",
path : "tenants/{tenantId}",
method : "GET",
nickname : "getTenantById",
summary : "Find Tenant by Id",
notes : "Returns a tenant by Id",
type : "Tenant",
produces : ["application/json"],
parameters : [params.path("tenantId","ID of the Tenant","string")],
responseMessages : [swe.invalid('tenantId')]
},
'action' : function(req,res){
if(!req.params.tenantId){
console.log("Tenants Id not provided");
return res;
}
var tenant = {
"id" : res.params.tenantId
}
res.send(JSON.stringify(tenant));
}
};
My package.json file:
{
"name": "myapp",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"body-parser": "~1.10.2",
"cookie-parser": "~1.3.3",
"debug": "~2.1.1",
"express": "~4.11.1",
"jade": "~1.9.1",
"morgan": "~1.5.1",
"serve-favicon": "~2.2.0",
"swagger-node-express": "~2.0"
}
}
The link to swagger-node-express : https://github.com/swagger-api/swagger-node-express
And the error I am getting after running node app.js command:
Users/deepaksharma/Documents/PROGRAMMING/sample-express-app/myapp/node_modules/swagger-node-express/Common/node/swagger.js:446
app[currentMethod](fullPath, function (req, res, next) {
^
TypeError: Cannot read property 'get' of null
at Swagger.addMethod (/Users/deepaksharma/Documents/PROGRAMMING/sample-express-app/myapp/node_modules/swagger-node-express/Common/node/swagger.js:446:8)
at /Users/deepaksharma/Documents/PROGRAMMING/sample-express-app/myapp/node_modules/swagger-node-express/Common/node/swagger.js:495:10
at Function.forOwn (/Users/deepaksharma/Documents/PROGRAMMING/sample-express-app/myapp/node_modules/swagger-node-express/node_modules/lodash/dist/lodash.js:1301:15)
at Swagger.addHandlers (/Users/deepaksharma/Documents/PROGRAMMING/sample-express-app/myapp/node_modules/swagger-node-express/Common/node/swagger.js:493:5)
at Swagger.addGet.Swagger.addGET (/Users/deepaksharma/Documents/PROGRAMMING/sample-express-app/myapp/node_modules/swagger-node-express/Common/node/swagger.js:520:8)
at Object.<anonymous> (/Users/deepaksharma/Documents/PROGRAMMING/sample-express-app/myapp/app.js:31:9)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
I cannot understand why I am getting a null error?
I figured it out! It is a silly mistake. I forgot to add models.model in line 30 of app.js. I am importing models.js into the variable models but not using the exported variable models.model in addModels() on line 30 of app.js.
This question can be closed because it does not add anything useful to the community.
im using ExpressJS 4.2 and PassportJS to authenticate local users.
Everything is fine except when I try to rise failureFlash message.
This is my conf, thanks in advance!
==== requires in app.js
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport')
var mongoose = require('mongoose');
var flash = require('connect-flash');
==== config in app.js
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser('secret'));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
==== /admin route (routes/admin.js)
router.post('/admin', passport.authenticate('loginAdmin',{ successRedirect: '/panel',
failureRedirect: '/admin',
failureFlash: true }));
==== passport file (config/passport.js)
passport.use('loginAdmin', new LocalStrategy(
function(username, password, done) {
modeloUsuario.findOne({ nombre: username, password: password }, function(err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
return done(null, user, {message: "invalid login"}); //<- error problem
});
}
));
==== Finally, my package.json
{
"name": "test",
"version": "0.0.2",
"private": true,
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express": "~4.2.0",
"connect-flash": "latest",
"static-favicon": "~1.0.0",
"morgan": "~1.0.0",
"cookie-parser": "~1.0.1",
"body-parser": "~1.0.0",
"debug": "~0.7.4",
"ejs": "~0.8.5",
"passport": "latest",
"passport-local": "latest",
"mongoose": "latest"
}
}
The error:
Github/express-auth/node_modules/passport/lib/middleware/authenticate.js:111
req.flash(type, msg);
^
TypeError: Object #<IncomingMessage> has no method 'flash'
You haven't initiliazed flash in your middleware in app.js.
Adding app.use(flash) before passport middleware should fix the problem.
See connect-flash #usage for more info.