Why this code doesn't work?
const whitelist = ['http://localhost:3000' , 'https://localhost:3443', 'http://localhost:4200','http://localhost:5000'];
const corsOptionsDelegate =(req: Request, callback: any) => {
let corsOptions;
console.log('origin' req.header('Origin'));
if(req.header('Origin') != null){
if(whitelist.indexOf(req.header('Origin')) !== -1){
console.log("index : " whitelist.indexOf(req.header('Origin')));
corsOptions = { origin : true};
}
else{
console.log('here else :' whitelist.indexOf(req.header('Origin')));
corsOptions = { origin : false };
}
}
callback(null , corsOptions);
};
ERROR:
Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'.
Error comes from (req.header('Origin'))
parentheses.
CodePudding user response:
The automatically-detected type for whitelist
is string[]
since you initialized it only with strings as elements.
The indexOf
method for a string[]
array then accordingly gets the signature indexOf(searchElement: string, fromIndex?: number | undefined): number
- note that searchElement
is a string
.
req.header
can return undefined
if the requested header does not exist, hence the type of its return value is string | undefined
and not just string
.
Therefore, by writing whitelist.indexOf(req.header('Origin'))
you are attempting to pass a string | undefined
to something that expects a string
.
You can solve this by first checking whether the header exists and only then test whether it's whitelisted (also, I'm going to use includes
here instead of indexOf
because you don't seem to use the actual index anyway other than in your debug log):
const origin = req.header('Origin')
if (origin !== undefined && whitelist.includes(origin) {
corsOptions = { origin: true }
} else {
corsOptions = { origin: false }
}
...which could be further simplified to this:
const origin = req.header('Origin')
corsOptions = { origin: origin !== undefined && whitelist.includes(origin) }
You could also use a default value for a missing origin header, say, an empty string, and then the code becomes even simpler:
corsOptions = { origin: whitelist.includes(req.header('Origin') ?? '') }