Cannot get Stored Cookies from browser in Express Js - node.js

Ive set user cookie as a jwt token in the browser and it is setted up successfully but when I try to get that cookie using req.cookies it gives me undefined and [object: null prototype] {}. Heres my code
exports.isAuthenticated = asyncErrorHandler(async (req, res, next) => {
//fetching the jwt token from the cookie
const { token } = req.cookies;
console.log(req.cookies);
if (!token) return next(new ErrorHandler("plz log in first ", 400));
//verifying the given token matches the jwt stored token
const decodedData = jwt.verify(token, process.env.JWT_SECRET);
req.user = await userModel.findById(decodedData.id);
next();
});
this is my express app.js file
const express = require("express");
const errorMiddleware = require("./middleware/error");
const cookieParser = require("cookie-parser");
const bodyparser = require("body-parser");
const fileupload = require("express-fileupload");
const cors = require("cors");
const app = express();
app.use(cookieParser());
app.use(express.json());
app.use(bodyparser.urlencoded({ extended: true }));
app.use(fileupload());
app.use(
cors({
credentials: true,
origin: "http://127.0.0.1:5173",
optionsSuccessStatus: 200,
})
);
// Route Imports
const productRoutes = require("./routes/productRoutes");
const userRoutes = require("./routes/userRoutes");
const orderRoutes = require("./routes/orderRoute");
const bodyParser = require("body-parser");
app.use("/api/v1", productRoutes);
app.use("/api/v1/user", userRoutes);
app.use("/api/v1", orderRoutes);
//error HAndler Middleware
app.use(errorMiddleware);
module.exports = app;
Ive tried cookie-parseer and also had cors in my express app file. ive set the cookie key as token

the req.cookies isn't the right way to get cookies
If you want to get cookies it is in the header so you must get cookies from header from the request like this :
console.log(req.headers.cookie)

Related

504 Gateway Timeout issue in expressjs while uploading file

Hi i am facing CORS issue in expressjs and nuxtjs while uploading files in production mode. things works fine on localhost but after i deploy to digital ocean, only one route where i upload file doesn't work.
here are the codes so far
this is app.js
const express = require('express');
const helmet = require('helmet');
const xss = require('xss-clean');
const mongoSanitize = require('express-mongo-sanitize');
const compression = require('compression');
const cors = require('cors');
const passport = require('passport');
const httpStatus = require('http-status');
const config = require('./config/config');
const morgan = require('./config/morgan');
const { jwtStrategy } = require('./config/passport');
const { authLimiter } = require('./middlewares/rateLimiter');
const routes = require('./routes/v1');
const { errorConverter, errorHandler } = require('./middlewares/error');
const ApiError = require('./utils/ApiError');
const app = express();
if (config.env !== 'test') {
app.use(morgan.successHandler);
app.use(morgan.errorHandler);
}
// set security HTTP headers
app.use(helmet());
// parse json request body
app.use(express.json());
// parse urlencoded request body
app.use(express.urlencoded({ extended: true }));
// sanitize request data
app.use(xss());
app.use(mongoSanitize());
// gzip compression
app.use(compression());
// enable cors
app.use(cors());
app.options('*', cors());
// jwt authentication
app.use(passport.initialize());
passport.use('jwt', jwtStrategy);
// limit repeated failed requests to auth endpoints
if (config.env === 'production') {
app.use('/v1/auth', authLimiter);
}
// v1 api routes
app.use('/v1', routes);
// send back a 404 error for any unknown api request
app.use((req, res, next) => {
next(new ApiError(httpStatus.NOT_FOUND, 'Not found'));
});
// convert error to ApiError, if needed
app.use(errorConverter);
// handle error
app.use(errorHandler);
module.exports = app;
this is upload.route.js inside routes folder
const express = require('express');
const uploadController = require('../../controllers/uploads.controller')
const router = express.Router();
router.post('/image', uploadController.setProductImages)
router.post('/image/activity', uploadController.uploadActivityImage)
module.exports = router;
this is index.js inside routes folder
const express = require('express');
const uploadRoute = require('./upload.route');
const config = require('../../config/config');
const router = express.Router();
const defaultRoutes = [
{
path: '/uploads',
route: uploadRoute
}
];
defaultRoutes.forEach((route) => {
router.use(route.path, route.route);
});
module.exports = router;
this is the error i am getting when i upload files.
cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at
https://v1api.thetripclub.com/v1/uploads/image/activity. (Reason: CORS
header ‘Access-Control-Allow-Origin’ missing). Status code: 504.
XHRPOSThttps://***.*******.com/v1/uploads/image/activity
CORS Missing Allow Origin

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.

req.cookies is null and I don't know why

I've looked at a few previous stack overflow posts but can't figure out why this is happening.
I have included cookie parser before all my routes and the cookie is in the browser. For some reason I just can't access it.
const cookieParser = require("cookie-parser");
const cors = require("cors");
const AppError = require("./utils/appError");
const globalErrorHandler = require("./controllers/errorController");
const dishRouter = require("./routes/dishRoutes");
const userRouter = require("./routes/userRoutes");
const orderRouter = require("./routes/orderRoutes");
const imageRouter = require("./routes/imageRouter");
const app = express();
app.use(cookieParser());
app.enable("trust proxy");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.options("*", cors());
ROUTES...
Here is how I am accessing the req.cookies
First I do an axios call
axios({
method: "patch",
url: `http://localhost:8080/api/v1/users/me`,
data: this.state,
})
Then it goes through this middleware
router
.route("/me")
.patch(authController.protect, userController.updateProfile)
In authController.protect I do the following
try {
//1) Getting token and check if it exists.
let token;
if (
//POSTMAN
req.headers.authorization &&
req.headers.authorization.startsWith("Bearer")
) {
token = req.headers.authorization.split(" ")[1];
} else if (req.cookies.jwt) {
token = req.cookies.jwt;
}
console.log(`TOKEN: ${token}`);
console.log(req.cookies);
The console.log right above gives null.
I faced a similar issue with my code where I was getting null when checking req.cookies. I used express for my node.js files and I followed the explanations from the following links:
http://expressjs.com/en/resources/middleware/cors.html
https://developers.google.com/web/updates/2015/03/introduction-to-fetch
So from server side I added configuration to cors() and set credentials: true and on client side from my fetch() request I added credentials: 'include' and this gave me access to the cookies on my browser. My fetch() request was making use of the PUT method.

CSRF Token in Mean Stack

I am not able to integrate CSRF token of express with XSRF TOKEN of Angular. I am using the given tutorial
https://jasonwatmore.com/post/2020/09/08/nodejs-mysql-boilerplate-api-with-email-sign-up-verification-authentication-forgot-password.
I know code is in rough style but I need to solve the issue.
Here is my code of express
server.js(main)
require('rootpath')();
const express = require('express');
const app = express();
const helmet = require("helmet");
const bodyParser = require('body-parser');
var cookieParser = require('cookie-parser')
var csrf = require('csurf')
const cors = require('cors');
const errorHandler = require('_middleware/error-handler');
app.use(cookieParser());
app.use(csrf({ cookie: true }))
app.use(helmet({ dnsPrefetchControl: { allow: true }}));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.all('*', function (req, res) {
res.cookie('XSRF-TOKEN', req.csrfToken())
})
app.use(cors({ origin: (origin, callback) => callback(null, true), credentials: true }));
// api routes
app.use('/accounts', require('./accounts/accounts.controller'));
// swagger docs route
app.use('/api-docs', require('_helpers/swagger'));
// global error handler
app.use(errorHandler);
// start server
const port = process.env.NODE_ENV === 'production' ? (process.env.PORT || 80) : 4000;
app.listen(port, () => console.log('Server listening on port ' + port));
In Angular I have added in XSRF TOKEN in module.ts
imports: [
BrowserModule,
ReactiveFormsModule,
HttpClientModule,
HttpClientXsrfModule.withOptions({
cookieName: 'XSRF-TOKEN',
headerName: 'X-XSRF-TOKEN'
}),
AppRoutingModule
],
Kindly Help me to sort out the issue
I have used different which solved my problem.
here is the link
https://www.npmjs.com/package/express-csrf-double-submit-cookie
const cookieParser = require('cookie-parser')
const csrfDSC = require('express-csrf-double-submit-cookie')
const express = require('express')
// create middleware
const csrfProtection = csrfDSC();
const app = express();
app.use(cookieParser());
// middleware to set cookie token
app.use(csrfProtection)
// protect /api
app.post('/api', csrfProtection.validate, function (req, res) {
res.status(200).end();
})
previously I was using
https://www.npmjs.com/package/csurf
for my single page application

How to access an API endpoint through a token using headers?

Currently I have a public api implemented, anyone can access it.
My intention is that the user now pass a token through the header so that they can access the data from the endpoints. But I don't know how to implement it in my code.
I appreciate your help!
router.get('/AllReports' , (req , res) =>{
PluginManager.reports()
.then(reports =>{
res.status(200).json({
reports
});
}).catch((err) =>{
console.error(err);
});
});
app.js
const express = require('express');
const morgan = require('morgan');
const helmet = require('helmet');
const cors = require('cors');
const bodyParser = require('body-parser');
const middlewares = require('./middlewares/index').middleware;
const api = require('./api');
const app = express();
app.use(morgan('dev'));
app.use(helmet());
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', (req, res) => {
res.json({
message: '🦄🌈✨👋🌎🌍🌏✨🌈🦄'
});
});
app.use('/api/v1', api);
app.use(middlewares);
module.exports = app;
To see a list of HTTP request headers, you can use :
console.log(JSON.stringify(req.headers));
Then you can check if token is valid and then
go on with processing.
Example
router.get('/', (req, res) => {
// header example with get
const authHeader = req.get('Authorization'); //specific header
console.log(authHeader);
// example with headers object. // headers object
console.log(req.headers);
});

Resources