【问题标题】:How to resolve a GET 404 (not found) error in MEAN application?如何解决 MEAN 应用程序中的 GET 404(未找到)错误?
【发布时间】:2017-08-28 20:54:40
【问题描述】:

我目前正在尝试在我正在构建的个人资料页面上获取(登录用户的)用户详细信息,但我收到此错误:

GET http://localhost:3000/users/undefined 404 (Not Found)
error_handler.js:54 EXCEPTION: Response with status: 404 Not Found for 
URL: http://localhost:3000/users/undefined

我认为这可能是对 json 数据进行字符串化的问题,但这似乎并没有改变任何东西,而且我读过 Angular 2 不再需要它。

我将 localhost:4200 用于 Angular,将 localhost:3000 用于 Express。当我在 localhost:3000/users/id (使用对象 id)上进行 api 调用时,它会很好地返回 json 数据。我不确定可能出了什么问题。

快速路线

router.get('/id', (req, res) => {
     console.log("getting a specific user");
     if(!mongoose.Types.ObjectId.isValid(req.params.id)) {
       return res.status(400).json({ message: 'Specified id is not valid' });
     }

     User.findById(req.params.id, (err, users) => {
       if (err) {
          return res.send(err);
        }

        return res.json(users);
      });


    });

角​​度服务

import { Injectable } from '@angular/core';
import { AuthService } from './auth.service';
import { Http, Headers, RequestOptions, Response } from '@angular/http';

@Injectable()
export class UserService {

  BASE_URL: string = 'http://localhost:3000';

  constructor(
    private http: Http,
    private authService: AuthService

  ) { }

  get(id) {
  let headers = new Headers({ 'Authorization': 'JWT ' + this.authService.token });
  let options = new RequestOptions({ headers: headers });
  return this.http.get(`${this.BASE_URL}/users/${id}`, options)
    .map((res) => res.json());
}

配置文件组件

import { Component, OnInit, Input } from '@angular/core';
import { AuthService } from '.././services/auth.service';
import { UserService } from '.././services/user.service'
import { Router, ActivatedRoute } from '@angular/router';


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

  currentUser;

  isAuth: boolean;

  constructor(
    private session: AuthService,
    private router:  Router,
    private userService: UserService,
    private route: ActivatedRoute

  ) {


  this.session.isAuth
       .subscribe((isAuth: boolean) => {
       // user will be false if logged out
       // or user object if logged in.
         this.isAuth = isAuth;
       });
   if (this.session.token) {
     this.isAuth = true;
     console.log(this.session);
   } else {
     this.isAuth = false;
   }

  }




  ngOnInit() {

    this.route.params.subscribe(params => {
      this.getUserDetails(params['id']);
    });


  }

  getUserDetails(id) {
     this.userService.get(id)
       .subscribe((user) => {
         this.currentUser = user;
         console.log(this.currentUser);
       });
   }


  }

【问题讨论】:

    标签: node.js angular express angular2-routing mean-stack


    【解决方案1】:

    请使用以下代码:

    快速路线

    router.get('/users/:id', (req, res) => {
    console.log("getting a specific user");
     if(!mongoose.Types.ObjectId.isValid(req.params.id)) {
      return res.status(400).json({ message: 'Specified id is not valid' });
     }
     else {
     User.findById(req.params.id, (err, users) => {
     if (err) {
        return res.send(err);
     }
     else {
        return res.json(users);
     }
    });
    }
    });
    

    角度服务

    import { Injectable } from '@angular/core';
    import { AuthService } from './auth.service';
    import { Http, Headers, RequestOptions, Response } from '@angular/http';
    
    @Injectable()
    export class UserService {
    
    BASE_URL: string = 'http://localhost:3000';
    
    constructor(
     private http: Http,
     private authService: AuthService
    
    ) { }
    
    get(id) {
    let headers = new Headers({ 'Authorization': 'JWT ' + this.authService.token   });
    let options = new RequestOptions({ headers: headers });
    return this.http.get(this.BASE_URL + '/users/' + id, options)
     .map((res) => res.json());
    }
    

    我希望,这可以满足您的需要。

    【讨论】:

    • 感谢您的建议。不幸的是,我收到了同样的错误。 ://
    • 您是否在 cmd 中收到此消息“正在获取特定用户”?
    • 这是一个 404(未找到)错误。目前我最好的猜测是我没有正确抓住 Angular 中的 ._id 参数,因为它确实在服务器中工作。但我在 cmd 中没有收到任何“获取特定用户”消息。
    • 我发现如果我手动将 id 放入 url,我可以在我的 Angular 2 个人资料页面上检索经过身份验证的用户数据。看起来我需要将 id 传递到我的 [routerLink] 个人资料网址中。但这在我的导航组件中。这意味着(当前)我的用户信息不适用于我的导航组件。我知道一定有更好的方法。
    猜你喜欢
    • 1970-01-01
    • 2015-02-08
    • 2021-02-16
    • 2017-06-09
    • 2019-08-25
    • 2017-01-17
    • 2019-12-10
    • 1970-01-01
    • 2020-11-06
    相关资源
    最近更新 更多