I am working in Angular,node-express API web app. I am getting Unauthorized even using cors. I am very new to asynchronous world. I show My code snippet below.
node-login API
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);
CORS-Config
let cors = require('cors');
app.use(cors());
app.options('*', cors());
also in same route file.
Angular-service
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)
}
)
}
}
note:Output
I am Getting response as
{
success:true,
message:"success",
token
}
at Mentioned response.So I am trying to redirect user to /dashboard. For that request I am getting unAuthorized from my API side.
I won't get sos from following questions. Angular returning 401 unauthorized Angular.js 401 Unauthorized Status Code Angular returning 401 unauthorized
Thanks in advance...!!
this.http.get('http://localhost:8000/dashboard', { headers: { Authorization: `Bearer ${this.token}`}})