簡體   English   中英

成功登錄Angular-node API后,即使使用CORS也會返回401(未經授權)

[英]401 (Unauthorized) after successful login Angular-node API even using CORS

我正在使用Angular,node-express API Web應用程序。 即使使用cors我也會獲得未經授權的cors 我對異步世界非常陌生。 我在下面顯示我的代碼段。

節點登錄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-配置

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM