http.post()未发送请求并获取错误:“指定的令牌无效”

时间:2019-04-29 08:09:59

标签: angular angular-cli

我是Angular CLI的新手,我想在Angular中编写登录组件,但是当我发出发布请求时,Angular http没有将请求发送到服务器,并且作为输出,我在控制台中收到此错误消息,并且任何请求尚未发送到服务器:

InvalidTokenError {message: "Invalid token specified"}
InvalidTokenError
    at Object../node_modules/jwt-decode/lib/index.js (http://localhost:26000/vendor.js:497368:31)
    at __webpack_require__ (http://localhost:26000/runtime.js:77:30)
    at Object../src/app/authentication/auth.service.ts (http://localhost:26000/main.js:584:68)
    at __webpack_require__ (http://localhost:26000/runtime.js:77:30)
    at Object../src/app/authentication/auth-guard.service.ts (http://localhost:26000/main.js:400:71)
    at __webpack_require__ (http://localhost:26000/runtime.js:77:30)
    at Object../src/app/modules/hub-administration-tool/hub-administration-tool.routing.module.ts (http://localhost:26000/main.js:12909:92)
    at __webpack_require__ (http://localhost:26000/runtime.js:77:30)
    at Object../src/app/modules/hub-administration-tool/hub-administration-tool.module.ts (http://localhost:26000/main.js:12697:98)
    at __webpack_require__ (http://localhost:26000/runtime.js:77:30)

这是身份验证组件:


import { Injectable } from '@angular/core';
import { HttpClient,HttpHeaders } from '@angular/common/http';
import { JwtHelperService } from '@auth0/angular-jwt';
import { map} from 'rxjs/operators';

import decode from 'jwt-decode';




interface TokenResponse {
  access_token: string
}

export interface TokenPayload {
  username: string
  password: string
}

@Injectable()
export class AuthService {
  constructor(public jwtHelper: JwtHelperService,
    private http: HttpClient) { }


  public login (user: TokenPayload) {

    const base = this.http.post<any>(`//localhost:25000/auth/login`, {   username: user.username,    password: user.password  },{ headers: new HttpHeaders().set('Content-Type', 'application/json') })
    const request = base.pipe(
        map((data : TokenResponse) => {
            console.log({data});
             if (data.access_token) {
                console.log(data.access_token)
             }
            return data
        })
    )
    return request
}

}

这是登录组件:

import { Component, OnInit, Input, TemplateRef, ContentChild } from '@angular/core';
import { AuthService, TokenPayload } from '../authentication/auth.service';
import { FormBuilder, FormGroup, Validators  } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { HttpClient,HttpRequest } from '@angular/common/http'

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

  credentials: TokenPayload = {
    username: '',
    password: ''
}

  loginForm: FormGroup;
  loading = false;
  submitted = false;
  returnUrl: string;

  @ContentChild(TemplateRef)
  @Input() layoutTemplate: TemplateRef<any>;
  constructor(private authService: AuthService,
              private formBuilder: FormBuilder,
              private router: Router,
              private route: ActivatedRoute,
              private http : HttpClient
              ) { }

  ngOnInit() {



  }


  login() {
    this.authService.login(this.credentials).subscribe( //get username and password from Html file
      () => {
          console.log("DONE" );
      },
      err => {
          console.error(err)
      }
  )


}

}

packages.Json

{
  "name": "administration-hub",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve --port 26000 --poll=2000",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^6.0.3",
    "@angular/common": "^6.0.3",
    "@angular/compiler": "^6.0.3",
    "@angular/core": "^6.0.3",
    "@angular/forms": "^6.0.3",
    "@angular/http": "^6.0.3",
    "@angular/platform-browser": "^6.0.3",
    "@angular/platform-browser-dynamic": "^6.0.3",
    "@angular/router": "^6.0.3",
    "@auth0/angular-jwt": "^2.0.0",
    "@progress/kendo-angular-buttons": "^4.0.0",
    "@progress/kendo-angular-charts": "3.3.0",
    "@progress/kendo-angular-dateinputs": "2 - 3",
    "@progress/kendo-angular-dropdowns": "2 - 3",
    "@progress/kendo-angular-excel-export": "1 - 2",
    "@progress/kendo-angular-grid": "^3.5.0",
    "@progress/kendo-angular-inputs": "2 - 3",
    "@progress/kendo-angular-intl": "^1.4.0",
    "@progress/kendo-angular-l10n": "^1.1.0",
    "@progress/kendo-angular-popup": "^2.0.0",
    "@progress/kendo-angular-upload": "^4.1.3",
    "@progress/kendo-data-query": "^1.0.0",
    "@progress/kendo-drawing": "^1.2.0",
    "@progress/kendo-theme-default": "latest",
    "@progress/kendo-ui": "^2018.2.704",
    "@types/cross-storage": "^0.8.29",
    "@types/jspdf": "^1.1.31",
    "core-js": "^2.5.4",
    "cross-storage": "^1.0.0",
    "hammerjs": "^2.0.0",
    "jspdf": "^1.4.1",
    "jwt-decode": "^2.2.0",
    "ngx-bootstrap": "^3.0.1",
    "ngx-color-picker": "^6.5.0",
    "rxjs": "^6.0.0",
    "rxjs-compat": "^6.0.0",
    "zone.js": "^0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.6.8",
    "@angular/cli": "~6.0.8",
    "@angular/compiler-cli": "^6.0.3",
    "@angular/language-service": "^6.0.3",
    "@types/core-js": "^2.5.0",
    "@types/jasmine": "~2.8.6",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.2.1",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~1.7.1",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.0",
    "karma-jasmine": "~1.1.1",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.3.0",
    "ts-node": "~5.0.1",
    "tslint": "~5.9.1",
    "typescript": "~2.7.2"
  }
}

我应该如何解决该问题?

1 个答案:

答案 0 :(得分:0)

当您得到的结果来自服务器并带有令牌时,它就是一个对象。因此,您应该进入对象并提取令牌。在您的代码中,未定义令牌,因此会出现错误。在您的组件中:

     const base = this.http.post<any>(`//localhost:25000/auth/login`, {   username: 
       user.username,    password: user.password  },{ headers: new 
      HttpHeaders().set('Content-Type', 'application/json') })
           const request = base.pipe(
         map((data : TokenResponse) => {
           console.log({data});    // is the respond object

           console.log(data['_body'].token) //// your token is here

          return data
              })
                )
            return request
            }

我希望它能起作用