错误:无法匹配任何路由。 URL 段:“配置文件”或加载资源失败:服务器响应状态为 401(未授权)

Posted

技术标签:

【中文标题】错误:无法匹配任何路由。 URL 段:“配置文件”或加载资源失败:服务器响应状态为 401(未授权)【英文标题】:Error: Cannot match any routes. URL Segment: 'profile' or Failed to load resource: the server responded with a status of 401 (Unauthorized) 【发布时间】:2020-01-31 02:54:18 【问题描述】:

我正在为 MEANAUTH 应用程序工作,我想使用 angular jwt 访问用户配置文件,当我尝试登录和访问用户配置文件 https://localhost:3000/prifile时,我得到 Failed to load resource: the server responded with a status of 401 (Unauthorized) 或当我尝试使用这些 url `http://localhost://localhost:3000/users/profile ``,我收到此错误未捕获(承诺):错误:无法匹配任何路由。 URL 段:“用户/个人资料” 错误:无法匹配任何路由。 URL 段:“用户/个人资料”

这是我的代码

auth.service.ts

import  Injectable  from '@angular/core';
import  HttpClient, HttpHeaders  from '@angular/common/http';
import 'rxjs/add/operator/map';
import  Observable  from 'rxjs';


@Injectable(
  providedIn: 'root'
)
export class AuthService 

   authToken: any;
   user: any;

  constructor(private http: HttpClient)  

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

    authenticateUser(user):Observable<any>
      let headers = new HttpHeaders();
      headers.append('Content-Type','application/json');
      return this.http.post('http://localhost:3000/users/authenticate', user , headers: headers)
      .map(res => res);

    

    getProfile():Observable<any>
      let headers = new HttpHeaders();
      this.loadToken();
      headers.append('Authorization', this.authToken);
      headers.append('Content-Type','application/json');
      return this.http.get('http://localhost:3000/users/profile', headers: headers)
      .map(res => res);

    

    storeUserDate(token, user)
      localStorage.setItem('id_token', token);
      localStorage.setItem('user', JSON.stringify(user));
      this.authToken = token;
      this.user = user;
    

    loadToken()
      const token = localStorage.getItem('id_token');
      this.authToken = token;
    

    logout()
      this.authToken = null;
      this.user = null;
      localStorage.clear();
    

  

profile.component.ts

import  Component, OnInit  from '@angular/core';
import  AuthService  from '../../services/auth.service';
import  Router  from '@angular/router';


@Component(
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css']
)
export class ProfileComponent implements OnInit 

  user: Object;

  constructor(private authService: AuthService, private router: Router)  

  ngOnInit() 
    this.authService.getProfile().subscribe(profile => 
      this.user = profile.user;
    ,
     err => 
       console.log(err);
       return false;
     );

  



profile.html

<div *ngIf="user">
  <h2 class="page-header">user.name</h2>
  <ul class="list-group">
    <li class="list-group-item">Username : user.username</li>
    <li class="list-group-item">Email : user.email</li>
  </ul> 
</div>

这是我的护照 restApi 代码,我的 rest 应用程序工作正常,但是当我尝试与 angular 客户端集成时,它会显示错误。

users.js

const express = require("express");
const router = express.Router();
const passport = require("passport");
const jwt = require("jsonwebtoken");
const config = require("../config/database");
const User = require("../models/user");

//Register
 router.post("/register", (req, res, next) => 
  //res.send('REGISTER');
  let newUser = new User(
    name: req.body.name,
    email: req.body.email,
    username: req.body.username,
    password: req.body.password
  );
  User.addUser(newUser, (err, user) => 
    if (err) 
      res.json( success: false, msg: "Failed to register user" );
     else 
      res.json( success: true, msg: "User registered" );
    
  );
);


//Authenticate
 router.post("/authenticate", (req, res, next) => 
  //res.send('AUTHENTICATE');
  const username = req.body.username;
  const password = req.body.password;
  User.getUserByUsername(username, (err, user) => 
    if (err) throw err;
    if (!user) 
      return res.json( success: false, msg: "User not found!" );
    
    User.comparePassword(password, user.password, (err, isMatch) => 
      if(err) throw err;
      if(isMatch)
        const token = jwt.sign(
          type: "user",
          data:
            _id: user._id,
            name: user.name,
            username: user.username,
            email: user.email
          
         ,config.secret,
           expiresIn: 604800
         
        );
        return res.json(
           success: true,
           token: "JWT "+ token,
            user:
            id: user._id,
            name: user.name,
            username: user.username,
            email: user.email
          
        );
        else
          return res.json(
             success: true,
             msg: "Worng Password."
          );
        
    );
  );
);



//Profile
router.get("/profile", passport.authenticate('jwt', session: false), (req, res, next) => 
 // res.send("PROFILE");
 res.json(user: req.user);
); 

/* router.get("/profile", passport.authenticate('jwt', session: false), (req,res) =>
  console.log(req.user);
 return res.json(
   req.user
 );
)
  */

module.exports = router;

passport.js

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

module.exports = function(passport)
    let opts = ;
    opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt');
    opts.secretOrKey = config.secret;
    passport.use(new JwtStrategy(opts, (jwt_payload, done) => 
        User.getUserById(jwt_payload.data._id, (err, user) => 
            if(err)
                return done(err, false);
            
            if(user)
                return done(null, user);
            else
                return done(null, false);
            
        );
    )
     );
  

任何帮助都非常感谢..

【问题讨论】:

【参考方案1】:

因为当您登录或注册时,您会获得 jwt 令牌作为响应,将该 jwt 令牌存储到 localstorage 中,当您当时对用户配置文件进行 api 调用时,从 localstorage 中获取该 jwt 令牌并附加您的标头。我希望它会为你工作。

【讨论】:

请检查我的代码并告诉问题在哪里@vivek bharda

以上是关于错误:无法匹配任何路由。 URL 段:“配置文件”或加载资源失败:服务器响应状态为 401(未授权)的主要内容,如果未能解决你的问题,请参考以下文章

错误:无法匹配任何路由。网址段:

Angular 8嵌套路由和多个路由器插座不起作用

在ZF2中发生404错误“请求的URL无法通过路由匹配”

无法匹配任何路由

ZF2路由器无法进行分段

Django之路由系统