我正在尝试向我的mLab数据库发出GET请求。我传递了一个带有请求的JWT令牌,并将其记录在客户端和服务器上。它在客户端上正确读取,但在服务器上显示为null。任何帮助将非常感激。我正在使用Node.js和Angular。 我对此很新,所以如果错误很明显,我会提前道歉 这是服务器的GET路由:
router.get('/', (req, res, next) => {
var decoded = jwt.decode(req.query.token);
console.log(decoded);
console.log('employees');
if(decoded) {
return Company.find({_id: decoded._id})
.populate('user', 'firstName')
.exec(function(err, company) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
res.status(200).json({
message: 'Success',
obj: company
});
});
} else {
return res.status(401).json({
title: 'Not authenticated',
error: {
message: 'Please create an account or sign in'
}
});
}
console.log(company);
});
这是客户:
getEmployees() {
const token = localStorage.getItem('token')
? '?token=' + localStorage.getItem('token')
: '';
console.log(token);
return this.http.get('http://localhost:3000/company' + token)
.map((response: Response) => {
const employees = response.json().obj;
console.log(employees);
let transformedEmployees: Employee[] = [];
for (let employee of employees) {
transformedEmployees.push(new Employee(
employee.firstName,
employee.lastName,
employee.email,
employee.password,
employee.jobTitle,
employee.isAdmin,
employee.tasks
));
}
console.log(transformedEmployees)
this.employees = transformedEmployees;
return transformedEmployees;
})
.catch((error: Response) => {
this.errorService.handleError(error.json());
return Observable.throw(error.json())
});
}
答案 0 :(得分:0)
您不应将令牌放在请求的Authorization
标题中。
您使用快速中间件解码令牌:
const myDecoder = (req, res, next) => {
req.user = jwt.decode(req.headers.authorization);
next();
}
然后,你放在路线上:
router.get('/', myDecoder, (req, res) => {
let user = req.user;
console.log(user);
console.log('employees');
if (user) { blah }
...
不应该将整个令牌传递给URL本身。