2017-05-23 105 views
0

我使用JWT's進行用戶登錄身份驗證,但是當我想要在/auth路由上進行POST時,我總是遇到以下錯誤。節點JS類型錯誤:祕密必須是字符串或緩衝區

(node:3385) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: secret must be a string or buffer

(node:3385) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

這裏是我的代碼

app.post('/auth', function (req, res, next) { 
    var username = req.body.username; 
    var password = req.body.password; 

    User.findOne({ 
     where: {username: username} 
    }).then(function (user) { 
     if(user){ 
      bcrypt.compare(req.body.password, user.password).then(function (passcheck) { 
       if(passcheck){ 
        var jwtUser = { 
         username: user.username, 
         name: user.name, 
         score: user.score, 
         accesslevel: "all" 
        }; 

        var token = jwt.sign(jwtUser, app.get('superSecretString'), { 
         expiresIn: 1440 //expires in 24 hours 
        }); 

        //callback(token); 

        res.json({ 
         success: true, 
         message: 'Here´s your token.', 
         token: token 
        }); 

        /* 
        var resp = {success: true, message: 'Heres your token.', token: token}; 
        response.write(JSON.stringify(resp)); 
        */ 
       }else{ 
        res.status(401).json({ 
         success: false, 
         message: 'Authentification failed. Password or Username wrong' 
        }); 
       } 
      }); 
     }else{ 
      res.status(401).json({ 
       success: false, 
       message: 'Authentification failed.' 
      }); 
     } 
    }).catch(next); 
}); 

感謝答案。

+2

林想你需要傳遞到jwt.sign正確的參數。我會從這個app.get('superSecretString')開始檢查錯誤。 –

+0

@MykolaBorysyuk thx,我在config.js中忘記了「module.exports」這個「s」 – pache

回答

1

問題是你沒有在配置文件中聲明爲祕密。 你可以做另一種說法

const token = jwt.sign(user, '123456', { 
        expiresIn: 60 * 24 // expires in 24 hours 
       }); 

刪除app.get('superSecretString'),並添加'123456'

相關問題