授权过程在Angular 5中无法正常工作

时间:2018-06-15 05:55:07

标签: angular angular5

我有这样的问题。我正在创建一个带节点的角度应用程序。在那里,我创建了一个基于令牌的登录系统,并将令牌和用户数据存储在本地存储中。

这是我的服务档案。

import { Injectable } from '@angular/core';
import { HttpClient , HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import {User} from "./user";


@Injectable()
export class UserService {
  user: any;
  authToken: any;
  // readonly baseURL = 'http://localhost:3000/user';
  constructor(private http: HttpClient) { }

  registerUser(user: User){
      let headers = new HttpHeaders();
      headers.append('Content-Type', 'application/json');
      return this.http.post('http://localhost:3000/user/register', user, {headers: headers});

  }

  loginUser(user){
    let headers = new HttpHeaders();
    headers.append('Content-Type', 'application/json');
    return this.http.post('http://localhost:3000/user/login', user, {headers: headers});

  }

  storeData(token, user){
    localStorage.setItem("tokenid", token);
    localStorage.setItem("user", JSON.stringify(user));
    this.authToken = token;
    this.user = user;
  }

  getProfile(){


    this.fetchToken();

    let headers = new HttpHeaders();
    headers.append('Authorization',this.authToken);
    console.log(headers.append('Authorization',this.authToken));
    headers.append('Content-Type','application/json');
    return this.http.get("http://localhost:3000/user/profile",{headers:headers})

  }

  fetchToken(){

    const token = localStorage.getItem("tokenid");
    this.authToken = token;

  }



}

这是我使用令牌加载数据的特定Web组件。

import { Component, OnInit } from '@angular/core';
import { UserService} from '../../shared/user.service';
import {Router} from "@angular/router";

@Component({
  selector: 'app-adminpannel',
  templateUrl: './adminpannel.component.html',
  styleUrls: ['./adminpannel.component.css'],
  providers: [UserService]
})
export class AdminpannelComponent implements OnInit {

  constructor(private userService: UserService,private router: Router) { }

  ngOnInit() {
    this.userService.getProfile().subscribe(res=>{
        console.log(res)
    })
  }

}

这是我的后端文件,我检查该用户是否有效。

const express = require('express');
var router = express.Router();

var  User  = require('../models/user');
var jwt = require('jsonwebtoken');
const config = require('../db');
const passport =require('passport');


router.post("/register",function (req,res) {
    const newUser = new User({
        username: req.body.username,
        name:  req.body.name,
        email: req.body.email,
        password: req.body.password,
    });

    User.saveUser(newUser, function (err,user) {
        if(!err){
            res.json({state:true, msg:"data Inserted"});
        }

        else{
            res.json({state:false, msg:"data Is Not Inserted"});
        }
    });
});

router.post("/login", function (req, res) {
    const email=req.body.email;
    const password = req.body.password;

    User.findByEmail(email, function (err, user) {
        if(err) throw err;

        if (!user){
            res.json({state:false,msg:"No user found"});
        }

        if(user) {
            User.passwordCheck(password, user.password, function (err, match) {
                if (err) {
                    res.json({state: false, msg: "your password is incorrect"});
                }

                if (match) {
                    const token = jwt.sign(user, config.secret, {expiresIn: 86400 * 3});
                    res.json(
                        {
                            state: true,
                            token: "JWT " + token,
                            user: {
                                id: user._id,
                                name: user.name,
                                username: user.username,
                                email: user.email

                            }
                        }
                    )

                }

                else {
                    res.json({state: false, msg: "password does not match"});
                }
            });

        }

    });
});

router.get('/profile', passport.authenticate('jwt', { session: false}), function(req, res) {
        res.json({user:req.user});
    }
);


module.exports = router;

这是我的护照Jwt策略配置文件。

const JwtStrategy = require('passport-jwt').Strategy,
    ExtractJwt = require('passport-jwt').ExtractJwt;
const config = require('../db');
const User = require('../models/user');

const opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
opts.secretOrKey = config.secret ;

module.exports = function (passport) {

    passport.use(new JwtStrategy(opts, function(jwt_payload, done) {


        User.findUserbyId({_id: jwt_payload._doc._id}, function(err, user) {
            if (err) {
                return done(err, false);
            }
            if (user) {
                done(null, user);
            } else {
                done(null, false);

            }
        });
    }))
}

当我用邮递员检查时,它会提供正确的输出,但是当我尝试加载管理面板时。它总是给我一个这样的错误。

zone.js:2969 GET http://localhost:3000/user/profile 401 (Unauthorized)
scheduleTask @ zone.js:2969
ZoneDelegate.scheduleTask @ zone.js:407
onScheduleTask @ zone.js:297
ZoneDelegate.scheduleTask @ zone.js:401
Zone.scheduleTask @ zone.js:232
Zone.scheduleMacroTask @ zone.js:255
scheduleMacroTaskWithCurrentZone @ zone.js:1114
(anonymous) @ zone.js:3001
proto.(anonymous function) @ zone.js:1394
(anonymous) @ http.js:2364
Observable._trySubscribe @ Observable.js:172
Observable.subscribe @ Observable.js:160
subscribeToResult @ subscribeToResult.js:23
MergeMapSubscriber._innerSub @ mergeMap.js:138
MergeMapSubscriber._tryNext @ mergeMap.js:135
MergeMapSubscriber._next @ mergeMap.js:118
Subscriber.next @ Subscriber.js:95
ScalarObservable._subscribe @ ScalarObservable.js:51
Observable._trySubscribe @ Observable.js:172
Observable.subscribe @ Observable.js:160
MergeMapOperator.call @ mergeMap.js:92
Observable.subscribe @ Observable.js:157
FilterOperator.call @ filter.js:61
Observable.subscribe @ Observable.js:157
MapOperator.call @ map.js:57
Observable.subscribe @ Observable.js:157
AdminpannelComponent.ngOnInit @ adminpannel.component.ts:16
checkAndUpdateDirectiveInline @ core.js:12411
checkAndUpdateNodeInline @ core.js:13935
checkAndUpdateNode @ core.js:13878
debugCheckAndUpdateNode @ core.js:14771
debugCheckDirectivesFn @ core.js:14712
(anonymous) @ AdminpannelComponent_Host.ngfactory.js? [sm]:1
debugUpdateDirectives @ core.js:14697
checkAndUpdateView @ core.js:13844
callViewAction @ core.js:14195
execEmbeddedViewsAction @ core.js:14153
checkAndUpdateView @ core.js:13845
callViewAction @ core.js:14195
execComponentViewsAction @ core.js:14127
checkAndUpdateView @ core.js:13850
callWithDebugContext @ core.js:15098
debugCheckAndUpdateView @ core.js:14635
ViewRef_.detectChanges @ core.js:11619
(anonymous) @ core.js:5918
ApplicationRef.tick @ core.js:5918
(anonymous) @ core.js:5751
ZoneDelegate.invoke @ zone.js:388
onInvoke @ core.js:4760
ZoneDelegate.invoke @ zone.js:387
Zone.run @ zone.js:138
NgZone.run @ core.js:4577
next @ core.js:5751
schedulerFn @ core.js:4342
SafeSubscriber.__tryOrUnsub @ Subscriber.js:243
SafeSubscriber.next @ Subscriber.js:190
Subscriber._next @ Subscriber.js:131
Subscriber.next @ Subscriber.js:95
Subject.next @ Subject.js:56
EventEmitter.emit @ core.js:4322
checkStable @ core.js:4725
onHasTask @ core.js:4773
ZoneDelegate.hasTask @ zone.js:441
ZoneDelegate._updateTaskCount @ zone.js:461
Zone._updateTaskCount @ zone.js:285
Zone.runTask @ zone.js:205
drainMicroTaskQueue @ zone.js:595
ZoneTask.invokeTask @ zone.js:500
invokeTask @ zone.js:1540
globalZoneAwareCallback @ zone.js:1566
error (async)
customScheduleGlobal @ zone.js:1666
ZoneDelegate.scheduleTask @ zone.js:407
Zone.scheduleTask @ zone.js:232
Zone.scheduleEventTask @ zone.js:258
(anonymous) @ zone.js:1831
desc.set @ zone.js:1244
ResourceLoaderImpl.get @ platform-browser-dynamic.js:548
DirectiveNormalizer._fetch @ compiler.js:3145
(anonymous) @ compiler.js:3341
DirectiveNormalizer._loadMissingExternalStylesheets @ compiler.js:3340
DirectiveNormalizer._normalizeTemplateMetadata @ compiler.js:3252
(anonymous) @ compiler.js:3180
then @ compiler.js:475
DirectiveNormalizer.normalizeTemplate @ compiler.js:3180
CompileMetadataResolver.loadDirectiveMetadata @ compiler.js:14914
(anonymous) @ compiler.js:34420
(anonymous) @ compiler.js:34419
JitCompiler._loadModules @ compiler.js:34416
JitCompiler._compileModuleAndComponents @ compiler.js:34374
JitCompiler.compileModuleAsync @ compiler.js:34268
CompilerImpl.compileModuleAsync @ platform-browser-dynamic.js:239
PlatformRef.bootstrapModule @ core.js:5578
(anonymous) @ main.ts:11
./src/main.ts @ main.bundle.js:193
__webpack_require__ @ inline.bundle.js:55
0 @ main.bundle.js:201
__webpack_require__ @ inline.bundle.js:55
webpackJsonpCallback @ inline.bundle.js:26
(anonymous) @ main.bundle.js:1
core.js:1449 ERROR HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: "Unauthorized", url: "http://localhost:3000/user/profile", ok: false, …}

有人可以帮助我将此令牌正确发送到后端吗?谢谢!

1 个答案:

答案 0 :(得分:1)

问题出在您的getProfile()方法中。 HttpHeaders 不可变。你可能想写:

  1. headers = headers.append(...);因为.append会返回克隆。
  2. 或者您可以将标题对象放在HttpHeaders上的headers = new HttpHeaders(<object_goes_here>)的构造函数中