401(未经授权)成功登录Angular-node API后即使使用CORS也是如此

我在 Angular,node-express API 网络应用程序中工作 . 即使使用 cors ,我也会获得未经授权 . 我对异步世界很新 . 我在下面显示了我的代码片段 .

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());

也在同一路径文件中 .

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)
            }
        )
    }
}

注意:输出

我正在回应

{
   success:true,
   message:"success",
   token
}

在提到的回应 . 所以我试图将用户重定向到 /dashboard . 对于那个请求,我从API方面获得了unAuthorized .

我不会从以下问题得到sos . Angular returning 401 unauthorized Angular.js 401 Unauthorized Status Code Angular returning 401 unauthorized

提前致谢...!!

回答(1)

2 years ago

在Angular /dashboard http调用中错过了 Headers . 所以代码看起来像

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})