Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 无法在NodejJS中使用JWT访问受保护的路由_Node.js_Express_Jwt_Express Jwt - Fatal编程技术网

Node.js 无法在NodejJS中使用JWT访问受保护的路由

Node.js 无法在NodejJS中使用JWT访问受保护的路由,node.js,express,jwt,express-jwt,Node.js,Express,Jwt,Express Jwt,我正在尝试使用jwt保护应用程序路由。我能够生成jwt并验证jwt,我已经创建了中间件authorize.js,我将在下面的代码中传递给/sec路由,但当我尝试使用jwt访问受保护路由时,它显示以下错误: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:518:11) at Serve

我正在尝试使用jwt保护应用程序路由。我能够生成jwt并验证jwt,我已经创建了中间件authorize.js,我将在下面的代码中传递给/sec路由,但当我尝试使用jwt访问受保护路由时,它显示以下错误:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:518:11)
at ServerResponse.header (D:\Backend\NodeJs\aws_test\node_modules\express\lib\response.js:771:10)
at ServerResponse.send (D:\Backend\NodeJs\aws_test\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (D:\Backend\NodeJs\aws_test\node_modules\express\lib\response.js:267:15)
at D:\Backend\NodeJs\aws_test\server.js:24:9
at Layer.handle [as handle_request] (D:\Backend\NodeJs\aws_test\node_modules\express\lib\router\layer.js:95:5)
at next (D:\Backend\NodeJs\aws_test\node_modules\express\lib\router\route.js:137:13)
at D:\Backend\NodeJs\aws_test\auth.js:21:20
at Object.module.exports [as verify] (D:\Backend\NodeJs\aws_test\node_modules\jsonwebtoken\verify.js:53:12)
at authorize (D:\Backend\NodeJs\aws_test\auth.js:11:13)
以下是我在《邮差》中设置jwt的方式:

下面是我的代码:

server.js

const express = require('express');
const jwt = require('jsonwebtoken');
const authorize = require('./auth');
const chalk = require('chalk');

const app = express();

const port = 3000 || process.env.PORT;

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

   res.send("Home page");
});

app.get('/jwt',(req,res) => {

   let token = jwt.sign({"body":"stuff"},"mypassphrase",{ algorithm: 'HS256'});
   console.log(chalk.blue(token));
});

app.get('/sec',authorize,(req,res) => {

   res.json({"name":"Hello digi"});
});

app.listen(port,(req,res) => {

  console.log(chalk.green(`App is running at ${port}`));
});
const fs =  require('fs');
const jwt = require('jsonwebtoken');

authorize = (req,res,next) => {

  if(typeof req.headers.authorization !== "undefined"){

      let token = req.headers.authorization.split(" ")[1];
      let key = fs.readFileSync('./private.pem','utf-8');

      jwt.verify(token, key,{ algorithm: "HS256" },(err,user) => {

         if (err) {  
            // shut them out!
            res.json({ error: "Not Authorized" });
           // throw new Error("Not Authorized");
         }
          // if the JWT is valid, allow them to hit
         // the intended endpoint
          return next();
       });
  }
 else{

    // No authorization header exists on the incoming
    // request, return not authorized and throw a new error 
    res.json({ error: "No Authorization header" });
   // throw new Error("Not Authorized");

    }    
}

module.exports = authorize;
auth.js

const express = require('express');
const jwt = require('jsonwebtoken');
const authorize = require('./auth');
const chalk = require('chalk');

const app = express();

const port = 3000 || process.env.PORT;

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

   res.send("Home page");
});

app.get('/jwt',(req,res) => {

   let token = jwt.sign({"body":"stuff"},"mypassphrase",{ algorithm: 'HS256'});
   console.log(chalk.blue(token));
});

app.get('/sec',authorize,(req,res) => {

   res.json({"name":"Hello digi"});
});

app.listen(port,(req,res) => {

  console.log(chalk.green(`App is running at ${port}`));
});
const fs =  require('fs');
const jwt = require('jsonwebtoken');

authorize = (req,res,next) => {

  if(typeof req.headers.authorization !== "undefined"){

      let token = req.headers.authorization.split(" ")[1];
      let key = fs.readFileSync('./private.pem','utf-8');

      jwt.verify(token, key,{ algorithm: "HS256" },(err,user) => {

         if (err) {  
            // shut them out!
            res.json({ error: "Not Authorized" });
           // throw new Error("Not Authorized");
         }
          // if the JWT is valid, allow them to hit
         // the intended endpoint
          return next();
       });
  }
 else{

    // No authorization header exists on the incoming
    // request, return not authorized and throw a new error 
    res.json({ error: "No Authorization header" });
   // throw new Error("Not Authorized");

    }    
}

module.exports = authorize;

我在上面的代码中做错了什么或者需要纠正什么。

唯一可能导致您看到的错误的执行路径是以下内容-在
autorize
中间件中:

     if (err) {  
        res.json({ error: "Not Authorized" });  // you're not returning here
     }

     return next();
在这里发生错误的情况下,当向客户端发送响应时,您没有将执行返回到调用代码,因此当前请求被转发到行中的下一个中间件-这将导致发送另一个响应

至于首先执行此路径的原因,从邮递员屏幕抓取判断,您为
授权
标题设置的值可能不正确-您将值设置为
jwt
,并将描述设置为实际的
令牌
,而实际上,您可能希望将值设置为两者的组合,并用类似
jwt标记的空格分隔