简体   繁体   中英

Parameter 'req' implicitly has an 'any' type - Typescript

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: 'brad@gmail.com'
  }

  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?

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) => {..}

You have to add the type of the parameter just after it.

app.get('/api', (req:any, res:any) => {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM