After setting a cookie in postman and firing a GET request to my express backend I see the cookie is undefined when I try to log it.
From the browser everything is fine. Out of nowhere this has happened. Any ideas?
I am using cookie parser.
const verifyToken = async (
req: Request,
res: Response,
next: NextFunction
): Promise<void | Response> => {
const { token } = req.cookies;
console.log('first', req.cookies.token);
Related
app.ts:
app.use(passport.authenticate("jwt", { session: false }));
// -------------------protected routes
//this home router returns the authenticated employee info
app.get("/home", (request: Request, response: Response) => {
response.json({ message: request.user });
});
// app.use("/employee", passport.authenticate("jwt", { session: false }));
app.use("/employee", employeeRouter);
// ------------ error handling. It only has 500 error, but later more errors will be handled.
app.use(function (err: Error, req: Request, res: Response, next: NextFunction) {
res.status(500).send({ error: "internal server error" });
console.error(err.stack);
next();
});
This is the code I have. at the first line, I set the jwt authentication as a global middleware, intending to set that any routers coming after this should be protected.
The router app. get("/home") can successfully access the authenticated user, and be able to send it as a response. However, the routers in the "employeeRouter" do not have access to the user and return undefined.
employeeRouter.ts
employeeRouter.get(
"/profile",
(request: Request, res: Response, next: NextFunction) => {
response.json({ message: request.user });
}
);
For example, this router is not in the app.ts file, and it is not able to access request.user.
Could anyone tell me how to fix it so that all of the files can access to the authenticated user?
I have created a cloud function with the following:
I'm trying to make an app/platform where a user can sign up for an account using Stripe Connect. I have a database with Firestore and the backend is using firebase cloud functions and nodejs.
const functions = require('firebase-functions');
const express = require('express');
const stripe = require('stripe')('sk_test_51XXX');
const admin = require('firebase-admin');
admin.initializeApp();
exports.createStripeUser = functions.https.onRequest((req, res) => {
var auth_code = stripe.oauth.token({
grant_type: 'authorization_code',
code: req.query.code,
});return res.send("Please close this page")
}
)
My problem is that I have an error where the req, res is. I don't know why there is an error, is the request wrong? What can I do so that I get no error and fix the problem?
If I hover on req, I get this message
(parameter) req: any
Parameter 'req' implicitly has an 'any' type.ts(7006)
I am using typescript
It seems you are using Typescript and req, res are implicitly of type any. You can import Request and Response from Express as shown below:
import { Request, Response } from "express"
export const createStripeUser = functions.https.onRequest((req: Request, res: Response) => {
// ...
})
And yes, explicitly adding any like (req: any, res: any) will remove that error too but that isn't the best thing to do.
Im new on nodeJS. Im developing a rest API using node and typescript. This api has to read an auth token from the request headers.
in order to do that, i have created a middleware to run on a GET endpoint.
import { Request, Response, NextFunction} from 'express'
export const verifyToken = (res: Response, req: Request, next: NextFunction) => {
//reading the headers
const token = req.headers['auth-token'];
if (!token){
return res.status(403).json({message: 'auth-token missing'})
}
next();
}
The problem is i cant read req.headers['auth-token'] because "Cannot read property 'auth-token' of undefined", so type a console.log(req.headers) to make sure its undefined, and it is.
Here is the console output:
(node:8372) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'auth-token' of undefined
Also, when i call the middleware in the endpoint, it throws an error that i cant understand
here is the route:
import Router from 'express'
import * as TiendaCtrl from '../controllers/tienda.controller'
import {verifyToken} from '../middlewares/verifyToken'
const router = Router();
//here is the endpoint
router.get('/tiendas', verifyToken , TiendaCtrl.getTiendas);
export default router;
VS code underlines "verifyToken" in the endpoint and this is what it says:
error TS2769: No overload matches this call.
[0] Overload 1 of 4, '(path: PathParams, ...handlers: RequestHandler<ParamsDictionary, any, any, ParsedQs>[]): Express', gave the following error.
[0] Argument of type '(res: Response, req: Request, next: NextFunction) => Response<any> | undefined' is not assignable to parameter of type 'RequestHandler<ParamsDictionary, any, any, ParsedQs>'.
[0] Types of parameters 'res' and 'req' are incompatible.
[0] Type 'Request<ParamsDictionary, any, any, ParsedQs>' is missing the following properties from type 'Response<any>': status, sendStatus, links, send, and 53 more.
[0] Overload 2 of 4, '(path: PathParams, ...handlers: RequestHandlerParams<ParamsDictionary, any, any, ParsedQs>[]): Express', gave the following error.
[0] Argument of type '(res: Response, req: Request, next: NextFunction) => Response<any> | undefined' is not assignable to parameter of type 'RequestHandlerParams<ParamsDictionary, any, any, ParsedQs>'.
[0] Type '(res: Response, req: Request, next: NextFunction) => Response<any> | undefined' is not assignable to type 'RequestHandler<ParamsDictionary, any, any, ParsedQs>'.
I have tried with:
const token = req.header('auth-token');
but it doesnt work either.
Im 100% sure of sending this auth-token header with POSTMAN
enter image description here
This is my app configuration:
import express from 'express'
import tiendasRoutes from './routes/tiendas.routes'
import authRoutes from './routes/auth.routes'
const app = express();
const bodyParser = require ('body-parser');
const cors = require('cors');
const morgan = require('morgan');
//Settings
app.set('port', process.env.PORT || 3000);
//Middlewares
app.use(morgan('dev'));
app.use(express.urlencoded({extended: true}));
app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}))
app.use(cors());
//Routes
app.use('/api',tiendasRoutes);
app.use('/api',authRoutes)
export default app;
export const verifyToken = (res: Response, req: Request, next: NextFunction) => {
//reading the headers
const token = req.headers['auth-token'];
if (!token){
return res.status(403).json({message: 'auth-token missing'})
}
next();
}
if you see it carefully, you will find that you have swapped the callback type of request and response, express first passes request callback then response callback, so first callback should be of Request Type, then Response, then NextFunction
so below is your correct updated middleware code
export const verifyToken = (req: Request, res: Response, next: NextFunction) => {
//reading the headers
const token = req.headers['auth-token'];
if (!token){
return res.status(403).json({message: 'auth-token missing'})
}
next();
}
I am trying to send HTTP POST request from the frontend to the backend. I first tried the backend with postman and it worked fine. However, when I tried it with the frontend it did not respond. There are no errors or warnings, it just does not post anything to the database and does not return a response. Here is my HTTP request from the frontend:
public addReg(UserOb) {
console.log("callingaddReg");
var headers = new Headers();
headers.append("content-type", "application/json");
console.log("headers appended");
return this.http
.post("http://localhost:3000/api/auth/register", UserOb)
.map(res => {
return res;
});
}
The above method logs headers appended in the console.
The backend method which handles the request is as follows:
router.post("/auth/register", isNotAuthenticated, authCtrl.register);
Here is the isNotAuthenticated middleware:
var isNotAuthenticated = function(req, res, next) {
// Check that the request doesn't have the JWT in the authorization header
var token = req.headers["authorization"];
if (token) {
return res.status(403).json({
error: null,
msg: "You are already logged in.",
data: null
});
}
next();
};
The end point location is in the index.js file
api
routes
index.js
Here is the URL to my monogdb: 'mongodb://localhost:27017/waterProject'
I try to set req user:
use(req: any, res: Response, next: () => {}) {
req.user = this.userService.getUserAuthenticated(req.cookies.t);
next();
}
but req.cookies is undefined.
to enable cookie I am using:
app.register(require('fastify-cookie'));
With ExecutionContext in Interceptor it is work well, but I need it for gourd , andcanActivate called before Interceptor.
Cookies get parsed in onRequest hook in app lifecycle of fastify so if its undefined, then your use take place before, or you have no cookies.
What can you do?
1)Parce cookies by hand from headers.raw.
2)Make your use as hook after onRequest handle of cookies.