【发布时间】:2018-06-26 05:13:16
【问题描述】:
我正在使用 NodeJs 学习 JWT。我被困在通过标头中的 JWT 实际上我不知道该怎么做。
index.js 文件
var express = require('express'),
app = express(),
routes = require('./routes'),
bodyParser = require('body-parser'),
path = require('path'),
ejs = require('ejs'),
jwt = require('jsonwebtoken');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.post('/home',routes.loginUser);
app.get('/', function(req, res) {
res.render('index');
});
app.get('/home',function(req, res) {
jwt.verify(req.token, 'qwertyu6456asdfghj', function(err, data) {
if (err) {
res.sendStatus(403);
}
});
});
app.listen(3000,function(){
console.log("Server running at Port 3000");
});
路由/index.js 文件
var jwt = require('jsonwebtoken');
exports.home = function(req, res){
res.render('home',{error: false});
};
exports.loginUser = function(req, res) {
var uname = req.body.Username;
var pwd = req.body.Password;
if(uname && pwd === 'admin'){
res.render('home');
var token = jwt.sign({ user: uname }, 'qwertyuiopasdfghj');
console.log('Authentication is done successfully.....');
console.log(token);
}
response.json({
authsuccess: true,
description: 'Sending the Access Token',
token: token
});
};
当我运行应用程序时,我在console.log 中获取令牌,但是
如何在 header 中传递令牌并将其存储在浏览器的 localStorage 中?
【问题讨论】:
-
这发生在客户端。你是从网络上调用你的快递应用程序吗?安卓? IOS?每个客户端都需要处理令牌并将其作为以下标头附加到请求:“Authorization”:“Bearer
”(“Bearer”只是将其与护照一起使用的约定) -
@ChicoDelaBarrio 我知道我该怎么做?
-
这取决于客户。我建议从使用邮递员link 开始测试您的请求
-
当我使用
res.json({ authsuccess: true, description: 'Sending the Access Token', token: token });发送响应时,我收到此错误 ->Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client -
这是因为你不能在 'resposnse.render' 之后使用 'respinse.json()'。您只能回复一次。此错误与 JWT 无关
标签: javascript node.js express json-web-token express-jwt