繁体   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