![](/img/trans.png)
[英]Express session not persisting after CORS calls in Angular-Node application
[英]401 (Unauthorized) after successful login Angular-node API even using CORS
我正在使用Angular,node-express API
Web应用程序。 即使使用cors
我也会获得未经授权的cors
。 我对异步世界非常陌生。 我在下面显示我的代码段。
app.post('/login',(req, res, next)=>{
var userCredentials={
email:req.body.email,
password:req.body.password
}
auth.login(userCredentials,(err,result)=> {
if(err) {
if(err=="notExist") {
res.json({
success:false,
message:"notExist"});
next()
}
else if(result=="success") {
let payload={
email: userCredentials.email,
}
let token = jwt.sign(payload, jwtOpts.secretOrKey);
res.json({
success:true,
message:"success",token});
// next()
}
app.get('/dashboard',passport.authenticate('jwt', {session: false}),tournament.getAllTournaments);
let cors = require('cors');
app.use(cors());
app.options('*', cors());
也在同一路由文件中。
login(credentials) {
return this.http.post('http://localhost:8000/login',credentials)
.subscribe(
response=> {
console.log(response)
if(response['success']) { /*note:OUTPUT*/
console.log(response)
this.token=response['token'];
this.http.get('http://localhost:8000/dashboard')
.subscribe(
response=> {
if(response['success']){
this.router.navigate(['/dashboard']);/*401 occurs here*/
}
else {
/*Error handler*/
}
}
)
}
else {
/*Error handler*/
}
},
error=> {
console.log(error)
}
)
}
}
我正在得到回应
{
success:true,
message:"success",
token
}
在提及的响应。所以我试图将用户重定向到/dashboard
。 对于该请求,我正在从API端获得未经授权的信息。
我不会因以下问题而感到困惑。 Angular返回401未经授权 Angular.js 401未经授权的状态码 Angular返回401未经授权
提前致谢...!!
Angular /dashboard
http调用中缺少标题。 所以代码看起来像
if(response['success']) {
this.token=response['token'];
let value='JWT '+this.token;
const header=new HttpHeaders({Authorization:value});
this.http.get('http://localhost:8000/dashboard',{headers:header})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.