0
我目前正试图获得用户的详细信息(的登录用户),我建立一个个人资料页面上,但我收到此错误:如何解决MEAN应用程序中的GET 404(未找到)错误?
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);
});
}
}
谢谢你的建议。不幸的是我收到了同样的错误。 :/ – universesurfer
您是否在cmd中收到了“获取特定用户”的消息? –
这是一个404(未找到)错误。我现在最好的猜测是,我没有正确地抓住Angular中的._id参数,因为它在服务器中工作。但是我没有在cmd中收到任何'获取特定用户'的信息。 – universesurfer