req cookies undefined express - node.js

I am lost as to why req cookies are always undefined in the expressJS. Here is my code:
const accessToken = jwt.sign({id:user._id}, process.env.JWT_TOKEN_SECRET)
console.log(accessToken)
res.cookie('authcookie',accessToken)
console.log(req.cookies.authcookie)
Here is the server.js code:
const express = require("express");
const app = express();
const morgan = require('morgan');
const bodyParser = require("body-parser");
const cors = require("cors");
const dotenv = require('dotenv');
const cookieParser = require('cookie-parser');
const path = require('path');
const userRoute = require('./routes/user')
dotenv.config()
const port = process.env.PORT || 5000
app.use(cors());
app.use(cookieParser())
app.use(morgan('dev'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:false}))
app.use('/api', userRoute)
Where did I go wrong? Many thanks in advance and greatly appreciate any helps. Thanks

Here is a working example:
server.js:
const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');
const cors = require('cors');
const cookieParser = require('cookie-parser');
const jwt = require('jsonwebtoken');
process.env.JWT_TOKEN_SECRET = 'secret';
const port = process.env.PORT || 5000;
app.use(cors());
app.use(cookieParser());
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/auth', (req, res) => {
const user = { _id: '123' };
const accessToken = jwt.sign({ id: user._id }, process.env.JWT_TOKEN_SECRET);
res.cookie('authcookie', accessToken);
res.sendStatus(200);
});
app.get('/api', (req, res) => {
console.log(req.cookies);
jwt.verify(req.cookies.authcookie, process.env.JWT_TOKEN_SECRET, (err, decoded) => {
if (err) {
console.log(err);
res.sendStatus(500);
return;
}
console.log('decoded jwt: ', decoded);
res.sendStatus(200);
});
});
app.listen(port, () => console.log(`HTTP server is listening on http://localhost:${port}`));
Open your browser with the http://localhost:5000/auth URL to get the authcookie cookie. Then access http://localhost:5000/api URL to call the api.
Output in the console:
HTTP server is listening on http://localhost:5000
GET /aut 404 2.095 ms - 142
GET /auth 200 4.047 ms - 2
{
authcookie: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEyMyIsImlhdCI6MTYxODgxODMyM30.mwCmW2NKSE9Youppnq_SCft7snYSp1Ud7nTThi7Q6Os'
}
decoded jwt: { id: '123', iat: 1618818323 }
GET /api 200 3.856 ms - 2

Related

Is There A Way To Fix This Cors Error On Heroku

I have a full stack app but when I uploaded my backend to heroku, on browsers cors policy is blocking my API routes. I get the error
No ‘Access-Control-Allow-Origin’ header is present on the requested resource.)
on heroku I get a 503 error for the routes. I am requesting https from an https origin on netlify which is my frontend. I tried to fix it but it does not solve all my cors errors.
index.js
const express = require("express");
const app = express();
const PORT = process.env.PORT || 8500
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const helmet = require("helmet");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const errorHandler = require("./middleware/error");
const cors = require("cors");
// setting cors
const corsOptions = {
origin: ['*', '*'],
preflightContinue:false,
credentials: true,
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
}
//Import Routes
const Routes = require('./routes/routes');
dotenv.config();
//middleware
app.use(cors(corsOptions));
app.use(express.json());
app.use(helmet());
app.use(bodyParser.json());
app.use(morgan("dev"));
app.use(cookieParser());
app.use("/api", Routes);
//welcome message
app.get('/', (req,res) => {
console.log("Welcome to the API.")
});
app.get('/greeting', (req,res) => {
res.json({greeting: 'Hello there'})
});
mongoose.connect(process.env.MONGO_URL, {useNewUrlParser: true, useUnifiedTopology: true}).then(() => {
console.log("MongoDB Connected")
})
.catch((err) => console.log(err));
app.listen(PORT, ()=> {
console.log("Backend server is running!")
})

just nodejs / route working but another routes doesn't working on cpanel

I created an API with node js express that works on localhost perfectly. but when I upload on the Cpanel just / route work and when I call another route that redirect to / route again
this is my server.js file
const http = require("http");
const express = require("express");
const app = express();
require("dotenv").config();
const helmet = require("helmet");
const bodyParser = require("body-parser");
const { nanoid } = require("nanoid/async");
const cors = require("cors");
//middleware
//json body
app.use(bodyParser.json());
//urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
//helmet
app.use(helmet());
app.use("/upload", express.static(process.cwd() + "/upload"));
const corsOptions = {
origin: "*",
credentials: true, //access-control-allow-credentials:true
optionSuccessStatus: 200,
};
app.use(cors(corsOptions));
const userRoute = require("./routes/userRoute");
app.use("/user", userRoute);
const provinceRoute = require("./routes/provinceRoute");
app.use("/province", provinceRoute);
const adverbRoute = require("./routes/adverbRoute");
app.use("/adverb", adverbRoute);
const catSubRoute = require("./routes/catSubRoute");
app.use("/category", catSubRoute);
const uploadRoute = require("./routes/upload");
app.use("/upload", uploadRoute);
app.use('/',(req,resp)=>{
resp.status(200).send("ok");
})
const server = http.createServer(app);
server.listen(process.env.PORT, () => {
console.log("server is running...");
});
module.exports = app;
and this is a route that I called with this URL
https://example.com/api/category/getallcats
const express = require("express");
const router = express.Router();
const catSubController = require("../controllers/catSubController");
router.get("/getallcats", catSubController.getAllCats);
module.exports = router;
and this return ok the same
https://example.com/api/ return ok on result

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.

form-data in node not showing

I have a node express set up.
While using Postman, Iam able to see data sent through x-www-form-urlencoded but the same is not being shown through form-data.
below are the codes
Server.js
const express = require('express')
var cors = require('cors')
const app = express()
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
var cookieParser = require('cookie-parser')
app.use(cookieParser())
app.use(cors())
const index = require("./routes/index")
app.use("/", index)
const port = process.env.PORT || 3060;
app.listen(port, function listenHandler() { console.log(`Running on ${port}`) });
Index.js
const express = require('express')
const router = express.Router()
var pool = require('./mysqlConnector')
const asyncMiddleware = require('./asyncMiddleware')
const func = require('./functions')
const time = new Date().toISOString().slice(0, 19).replace('T', ' ')
const nodemailer = require("nodemailer");
router.use('/auth', require('./auth')
Auth .js
const express = require('express')
const router = express.Router();
var pool = require('./mysqlConnector')
const asyncMiddleware = require('./asyncMiddleware')
const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs')
const nodemailer = require("nodemailer");
const func = require('./functions')
router.post('/register', asyncMiddleware( async(req, res, next) => {
res.send({ success: true, message: req.body })
}))
You should use Multer to handle form-data.
Multer is a node.js middleware for handling multipart/form-data
body-parser middleware can't handle multipart/form-data.
This does not handle multipart bodies, due to their complex and typically large nature.
In case you need to handle a text-only multipart form, you should use the .none() method:
E.g.
const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');
const upload = multer();
const app = express();
app.use(upload.none());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/auth/register', (req, res) => {
res.send({ success: true, message: req.body });
});
const port = process.env.PORT || 3060;
app.listen(port, function listenHandler() {
console.log(`Running on ${port}`);
});
postman:

NODE Cannot GET routes function

I have created a folder testint
My testint/app.js having following code
const express = require('express'); const path = require('path');
const bodyParser = require('body-parser'); const cors = require('cors');
const passport = require('passport'); const mongoose = require('mongoose');
const app = express(); const port = 7000; app.use(cors());
app.use(bodyParser.json());
app.use('/users', users); //Not working
app.get('/',(req,res) => {
res.send("Invalid Endpoint");
});
app.listen(port, () =>{
console.log('Server started on port '+ port);
});
testint/routes/users.js contains :
const express = require('express'); const router = express.Router();
res.send('Authenticate');
router.get('/register',(req, res, next) => {
res.send('REGISTER');
});
module.exports = router;
If I run http://localhost:7000/users/register
Am getting :
Cannot GET /users/register
I dint know where am wrong and am new to node any help will be appreciated.
I got solution. I didn't include
const users = require('./routes/users');
in app.js
and res.send('Authenticate'); in users.js is not required for instance.

Resources