Postman keeps loading on sending POST request to an express route - node.js

I created a route and controller for my sign up.
Here's my route:
const express = require("express");
const router = express.Router();
const { signup } = require("../../controllers/auth");
router.post("/signup", signup);
module.exports = router;
And here's my controller:
exports.signup = () => (req, res) => {
const { name, email, password } = req.body;
res.json({
user: { name, email, password },
});
};
Inside my server.js file I register both:
const express = require("express");
const morgan = require("morgan");
const cookieParser = require("cookie-parser");
const cors = require("cors");
const mongoose = require("mongoose");
require("dotenv").config();
// routes
const blogRoutes = require("./routes/blog");
const authRoutes = require("./routes/auth");
// app
const app = express();
// db
mongoose
.connect(process.env.DATABASE, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log("DB connected!"));
// middlewares
app.use(morgan("dev"));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cookieParser());
// cors
if (process.env.NODE_ENV == "development") {
app.use(cors({ origin: `${process.env.CLIENT_URL}` }));
}
// routes middleware
app.use("/api", blogRoutes);
app.use("/api", authRoutes);
// port
const port = process.env.PORT || 8000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Now on my POSTMAN, I tried to put the data using POST http://localhost:8000/api/signup with the header and raw setup right.
{
"name": "SyRyan",
"email": "syryan#gmail.com",
"password": "brace1010"
}
The database is connected but the postman takes forever to load the json request back. Am I making any mistakes here? Please help!

I think that the problem is that signup is a function that returns a function, but it should be just a function that receives req & res as parameters:
exports.signup = (req, res) => {
const { name, email, password } = req.body;
res.json({
user: { name, email, password },
});
};

Related

"Indicate whether to send a cookie in a cross-site request by specifying its SameSite attribute"

Hey I am working on a stripe project which redirect the user to stripe portal for payment but got stuck when I got this error :
Indicate whether to send a cookie in a cross-site request by specifying its SameSite attribute?
Here is my server.js in which I also has set the header :
const express = require('express')
const morgan = require('morgan')
const connectDB = require('./config/db')
const bodyParser = require('body-parser')
const cors = require('cors')
const jwt = require('jsonwebtoken')
const uuid = require("uuid")
// Config dotev
require('dotenv').config({
path: './config/config.env'
})
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY)
const app = express()
// Connect to database
connectDB();
// body parser
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
//header
app.use((req,res) => {
res.cookie('cookie', 'value', { sameSite: 'none', secure: true })
})
// Load routes
const authRouter = require('./routes/auth.route')
const stripeRouter = require('./routes/stripe.route')
// Dev Logginf Middleware
if (process.env.NODE_ENV === 'development') {
app.use(cors({
origin: process.env.CLIENT_URL
}))
app.use(morgan('dev'))
}
// Use Routes
app.use('/api', authRouter)
app.use('/api' , stripeRouter)
app.use((req, res) => {
res.status(404).json({
success: false,
msg: "Page not founded"
})
})
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
});

TypeError: authJwt is not a function

I am doing an e-shop project using MERN stack in that I faced the above error
app.js:
const express = require("express");
const app = express();
const morgan = require("morgan");
const mongoose = require("mongoose");
const cors = require("cors");
require("dotenv/config");
const authJwt = require('./helpers/jwt');
app.use(cors());
app.options("*", cors());
//middleware
app.use(express.json());
app.use(morgan("tiny"));
app.use(authJwt());
//Routes
const categoriesRoutes = require("./routes/categories");
const productsRoutes = require("./routes/products");
const usersRoutes = require("./routes/users");
const ordersRoutes = require("./routes/orders");
const api = process.env.API_URL;
app.use(`${api}/categories`, categoriesRoutes);
app.use(`${api}/products`, productsRoutes);
app.use(`${api}/users`, usersRoutes);
app.use(`${api}/orders`, ordersRoutes);
//Database
mongoose
.connect(process.env.CONNECTION_STRING, {
useNewUrlParser: true,
useUnifiedTopology: true,
dbName: "animal-feedmart-database",
})
.then(() => {
console.log("Database Connection is ready...");
})
.catch((err) => {
console.log(err);
});
//Server
app.listen(3000, () => {
console.log("server is running http://localhost:3000");
});
Near app.use(authJwt()) it is showing error.
Can anyone help me to solve the error
Thanks in advance
// Auth JWToken
const {authJwt} = require('./helpers/jwt')
// Middleware
app.use(authJwt);
// JWT
https://i.stack.imgur.com/3D2tD.png
i try this modification and it works try and see the results
const { expressjwt: jwt } = require("express-jwt")
function authJwt(){
let secret = process.env.SEC_TOK;
return jwt({
secret,
algorithms: ['HS256']
})
}
module.exports = authJwt;

Getting an undefined token of add category in console

I am new to React and Node and I'm getting an undefined token in console when I add category I get undefined in the console. I am using cookie-parser.
server.js file:
const express = require('express');
const app = express();
const cors = require('cors');
const morgan = require('morgan');
const cookieParser = require('cookie-parser')
const connectDB = require('./database/db');
const authRoutes = require('./routes/auth');
const categoryRoutes = require('./routes/category');
//middleware
app.use(cors());
//dev specifies it is for development
app.use(morgan('dev'));
//express.json allows us to parse incoming request in json in the format of a json
app.use(express.json());
app.use(cookieParser());
app.use('/api/auth', authRoutes);
//route for category
app.use('/api/category', categoryRoutes);
connectDB();
app.get('/', (req,res) => {
res.send('Inside Server');
});
const port = process.env.PORT || 5000;
app.listen(port, ()=>console.log(`Listening on port ${port}`));
category.js (controller file)
exports.create = (req,res) => {
setTimeout(()=> {
res.json({
successMessage: `${req.body.category} was created!`
});
}, 5000);
};
category.js (routes file)
const express = require('express');
const router = express.Router();
const categoryController = require('../controllers/category');
const { authenticateJWT } = require('../middleware/authenticator');
router.post('/', authenticateJWT , categoryController.create);
module.exports = router;
authenticator.js (middleware file)
const jwt = require('jsonwebtoken');
const { jwtSecret } = require('../config/keys');
exports.authenticateJWT = (req, res, next) => {
const token = req.cookies.token;
console.log(token);
}
keys.js file
//it is gonna tell us/ signifying if we are live if in develoopment or in production
const LIVE = false;
if (LIVE) {
module.exports = require('./prod.js');
} else {
module.exports = require('./dev.js');
}
Console screen:
Instead of undefined i should be getting token.
Any help will be highly appreciated.
Thanks!
Is there a token Cookie available? (You can check using the inspector of your browser, normally in the „application“ tab. If you are sending the request using any tools like postman, curl, wget, …, you have to set the cookie first.)
Was the cookie available on any other routes? What’s the difference between these routes and the category route? Is it possible that your cookie is constrained to a specific path, e.g. to /api/auth? If so, adjust the path in res.cookie.

My Local Host is keep loading although my mongodb server is connected amd running

I am following the brad Traversy Nodejs Tutorial my server is connected and started also my Mongodb connection is running but localhost keep loading and not responding.
I have checked my URL for mongo connection also the password and username all are correct. I have also allow network access from all sources.
This was perfectly working before but now this keeps loading and loading
my db.js
const mongoose = require("mongoose")
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true
})
console.log(`MongoDB connected ${conn.connection.host}`)
} catch (err) {
console.error(err)
process.exit(1)
}
}
module.exports = connectDB
my app.js
const express = require("express")
const path = require("path")
const dotenv = require('dotenv')
const morgan = require('morgan')
const exphbs = require('express-handlebars')
const passport = require('passport')
const connectDB = require('./config/db')
const routes = require('./routes/index')
const session = require("express-session")
const MongoDBStore = require('connect-mongodb-session')(session);
const mongoose = require('mongoose')
const methodOverride = require('method-override')
//locad config
dotenv.config({ path: './config/config.env' })
connectDB()
//passport config
require('./config/passport')(passport)
const app = express()
const PORT = process.env.PORT || 5000
//body parser
app.use(express.urlencoded({ extended: false }))
app.use(express.json())
//method override
// Method override
app.use(
methodOverride(function (req, res) {
if (req.body && typeof req.body === 'object' && '_method' in req.body) {
// look in urlencoded POST bodies and delete it
let method = req.body._method
delete req.body._method
return method
}
})
)
//logging
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'))
}
//handlebars helpers
const { formatDate, truncate, stripTags, select } = require('./helpers/hbs')
//Hnadlebars
app.engine('.hbs', exphbs({ helpers: { formatDate, truncate, stripTags, select }, defaultLayout: 'main', extname: '.hbs' }));
app.set('view engine', '.hbs');
//sessions
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUnitialized: false,
store: new MongoDBStore({
mongooseConnection: mongoose.connection
})
//cookie: { secure: true }
}))
//set passport middleware
app.use(passport.initialize())
app.use(passport.session())
//set global variable
app.use(function (req, res, next) {
res.locals.user = req.user || null
})
//static folder
app.use('/', express.static(path.join(__dirname, 'public')))
//Routes
app.use('/', routes);
app.use('/auth', require('./routes/auth'));
app.use('/stories', require('./routes/stories'));
//listen
app.listen(PORT, console.log(
`server is running in ${process.env.NODE_ENV} mode on port ${PORT}`
))
my ./routes/index.js
const express = require('express')
const router = express.Router()
const { ensureAuth, ensureGuest } = require('../middleware/auth')
const Story = require('../models/story')
//#desc Login/Landing Page
//#route GET/
router.get('/', ensureGuest, (req, res, next) => {
res.render("login", {
layout: "login"
})
})
//#desc Login/Landing Page
//#route GET/
router.get('/dashboard', ensureAuth, async (req, res, next) => {
console.log(req.user)
try {
const stories = await Story.find({ user: req.user._id }).lean() //plain Js object
res.render("dashboard", {
name: req.user.firstName,
stories
})
} catch (error) {
console.log('Stories error', error)
res.render('error/500')
}
})
module.exports = router
my browser
I have found if you're using middlewares then must call next function at the end this was the reason my page wasn't loading
The error was at //set global variable middleware

Results from Node/Express using Postgres never send even though they appear in the console

My node/Express app is displaying strange behavior.
I have the following code:
// app.js
const express = require('express');
const router = require('express').Router();
const bodyParser = require('body-parser');
const dotenv = require('dotenv');
const path = require('path');
const cors = require('cors');
dotenv.config({ path: path.resolve(__dirname, '.env.local') });
dotenv.config();
const port = process.env.PORT || 5000;
const passport = require('passport');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const PostgreSqlStore = require('connect-pg-simple')(session);
const app = express();
app.use(express.static(path.join(__dirname, 'build')));
app.use(cors());
app.options('*', cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser(process.env.SECRET_KEY));
app.use(session({
store: new PostgreSqlStore({
conString: `postgres://${process.env.DB_USER}:${process.env.DB_PASS}#${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_NAME}`,
}),
secret: process.env.SECRET_KEY,
resave: false,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
require('./auth/passport.js')(passport);
const routes = require('./api/routes')(router, passport);
app.use('/', routes);
app.listen(port, () => {
console.log(`App running on port ${port}.`)
})
module.exports = app;
// /api/routes.js
const api = require('./api');
module.exports = function(router, passport) {
router.get('/users', (req, res, next) => {
api.getUsers(req, res, next);
})
return router;
}
// /api/api.js
const Promise = require('bluebird');
const initOptions = {
promiseLib: Promise,
}
const pgp = require('pg-promise')(initOptions);
const db = pgp({
user: process.env.DB_USER,
host: process.env.DB_HOST,
database: process.env.DB_NAME,
password: process.env.DB_PASS,
port: process.env.DB_PORT,
});
const getUsers = (req, res, next) => {
db.task(t => {
return t.any('SELECT * FROM users ORDER BY uuid ASC')
.then((result) => {
res.json(result);
})
.catch(error => console.error(error));
})
}
module.exports = {
db,
getUsers,
}
If I run the server and cURL localhost:5000/users the app just sits there and doesn't return any data. However, if I Ctrl + C to stop the server connection, it gives me the following:
curl: (18) transfer closed with 1 bytes remaining to read
The weird thing is that this is followed by the data that's missing! I.e. it's not getting sent until the server is shut down.
Postman call never gives a response.
Console.logging result outputs the expected/missing data in the console.
The data's there, but res.send and res.json are doing nothing. I'm sure it has to do with Promises, but I'm not sure what I'm missing. I've also tried to use Pools and Clients for the database queries, instead of pg-promise, but to the same result.
I figured out the issue. I needed to use Pool correctly and tie it into the session.
// app.js
const express = require('express');
const router = require('express').Router();
const bodyParser = require('body-parser');
const dotenv = require('dotenv');
const path = require('path');
dotenv.config({ path: path.resolve(__dirname, '.env.local') });
dotenv.config();
const pool = require('./api/api').pool;
const cors = require('cors');
const port = process.env.PORT || 5000;
const passport = require('passport');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const PostgreSqlStore = require('connect-pg-simple')(session);
const app = express();
app.use(express.static(path.join(__dirname, 'build')));
app.options('*', cors());
app.use('*', bodyParser.json());
app.use('*', bodyParser.urlencoded({ extended: true }));
app.use(cookieParser(process.env.SECRET_KEY));
app.use(session({
store: new PostgreSqlStore({
pool,
}),
secret: process.env.SECRET_KEY,
resave: false,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
require('./auth/passport.js')(passport);
const routes = require('./api/routes')(router, passport);
app.use('/', routes);
app.listen(port, () => {
console.log(`App running on port ${port}.`)
})
module.exports = app;
// api/routes.js
const api = require('./api');
module.exports = function(router, passport) {
router.get('/users', (req, res, next) => {
api.getUsers(req, res, next);
})
return router;
}
// api/api.js
const Pool = require('pg').Pool
const pool = new Pool({
user: process.env.DB_USER,
host: process.env.DB_HOST,
database: process.env.DB_NAME,
password: process.env.DB_PASS,
port: process.env.DB_PORT,
});
const getUsers = (req, res, next) => {
pool.connect((err, client, done) => {
if (err) {
throw err
}
return client.query('SELECT * FROM users ORDER BY uuid ASC', (err, result) => {
if (err) {
console.error(error);
} else if (result.rowCount > 0) {
res.send(result.rows);
}
else {
res.sendStatus(500);
}
})
})
}
module.exports = {
pool,
getUsers,
}

Resources