Reputation: 111
I am new to typescript, I am trying to learn how to use Json Web Token to authenticate a typescript API but I am getting this error whenever I do npm start.
Parameter 'req' implicitly has an 'any' type.
19 app.get('/api', (req, res) => {
~~~
Parameter 'res' implicitly has an 'any' type.
19 app.get('/api', (req, res) => {
This is my code, it is just a simple authentication with JWT
app.get('/api', (req, res) => {
res.json({
message: 'Welcome to the API'
});
});
app.post('/api/posts', verifyToken, (req, res) => {
jwt.verify(req.token, 'secretkey', (err, authData) => {
if(err) {
res.sendStatus(403);
} else {
res.json({
message: 'Post created...',
authData
});
}
});
});
app.post('/api/login', (req, res) => {
// Mock user
const user = {
id: 1,
username: 'brad',
email: '[email protected]'
}
jwt.sign({user}, 'secretkey', (err, token) => {
res.json({
token
});
});
});
function verifyToken(req, res, next) {
const bearerHeader = req.headers['authorization'];
if(typeof bearerHeader !== 'undefined') {
const bearer = bearerHeader.split(' ');
const bearerToken = bearer[1];
req.token = bearerToken;
next();
} else {
res.sendStatus(403);
}
}
how can I fix this error?
Upvotes: 1
Views: 4431
Reputation: 346
You have to add the type of the parameter just after it.
app.get('/api', (req:any, res:any) => {
Upvotes: -1
Reputation: 5446
If you are using express:
import { Request, Response } from 'express'
app.get('/api', (req: Request, res: Response) => {..}
You can be general and write the code as: (not advised)
app.get('/api', (req: any, res: any) => {..}
Upvotes: 1