我正在开发通过 JWT 和 Angular 2 授权的 Web 应用程序。我在 Angular2 上有带有 API 的 Nodejs/express 服务器和客户端。 因此,我的服务器正确响应 GET 请求并提供如下数据:
{
“成功”:真实,
“用户”:{
"_id": "5a6ef70edb04dd29e24bb03b",
“电子邮件”:“丹科”,
“用户名”:“伊万”
}
}
接下来,这是我的auth.service.ts。函数createAuthenticationHeaders() 和 getProfile() 参与处理 HTTP 响应:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpRequest, HttpResponse, HttpParams} from '@angular/common/http';
import { Http, Headers, RequestOptions} from '@angular/http'; // Http, Headers, RequestOptions
import 'rxjs/add/operator/map';
@Injectable()
export class AuthService {
domain = "http://localhost:8080";
authToken;
user;
options;
constructor(
private http: HttpClient,
private httplegacy: Http) { }
createAuthenticationHeaders() {
this.loadToken();
this.options = new RequestOptions({
headers : new Headers({
'Content-Type' : 'application/json',
'authorization' : this.authToken
})
});
}
loadToken() {
this.authToken = localStorage.getItem('token');
}
registerUser(user) {
return this.http.post(this.domain + '/authentication/register', user);
}
loginUser(user) {
return this.http.post(this.domain + '/authentication/login', user);
}
storeUserData(token, user) {
localStorage.setItem('token', token);
localStorage.setItem('user', JSON.stringify(user));
this.authToken = token;
this.user = user;
}
getProfile() {
this.createAuthenticationHeaders();
return this.httplegacy.get(this.domain + '/authentication/profile', this.options);
}
}
此外,这是我的profile.component.ts:
import { Component, OnInit } from '@angular/core';
import { AuthService} from '../../services/auth.service';
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
username;
email;
constructor(
private authService: AuthService
) { }
ngOnInit() {
this.authService.getProfile().subscribe(profile => {
console.log(profile);
this.username = profile.user.username;
this.email = profile.user.email;
})
}
}
这些代码行的预期行为:使用 auth.service.ts 处理服务器对用户数据的响应(主要是createAuthenticationHeaders() 和 getProfile() 函数) ,用户的数据被传输到 profile.component.ts 以使用以下代码将其显示在网页上:
<h2 class="page-header">Profile Page</h2>
<ul class="list-group">
<li class="list-group-item">Username: {{ username }} </li>
<li class="list-group-item">Email: {{ email }}</li>
</ul>
但是,在编译时出现错误:“Response”类型上不存在属性“user”。您想解释一下为什么我会遇到这样的错误以及如何修复它吗?
P.S.:是的,console.log(profile) 给了我这样的信息:
Response {_body: "{"success":true,"user":{"_id":"5a6ef70edb04dd29e24bb03b","email":"danko","username":"ivan"}}", status: 200, ok: true, statusText: "OK", headers: Headers, …}
headers:Headers {_headers: Map(1), _normalizedNames: Map(1)}
ok : true
status : 200
statusText : "OK"
type : 2
url : "http://localhost:8080/authentication/profile"
_body : "{"success":true,"user":{"_id":"5a6ef70edb04dd29e24bb03b","email":"danko","username":"ivan"}}"
__proto__ : Body
constructor : ƒ Response(responseOptions)
toString : ƒ ()
__proto__ :
Object
但是如何从响应的 _body 字段获取数据?
P.S.:服务器端路由器的代码:
router.get('/profile', (req, res) => {
User.findOne({ _id: req.decoded.userId }).select('username email').exec((err, user) => {
if (err) {
res.json({ success: false, message: err });
} else {
if(!user) {
res.json({ success: false, message: 'User not found'});
} else{
res.json({ success: true, user: user });
}
}
});
});
最佳答案
您尝试直接从 express
的 Response
对象读取您的数据
。你需要这样的东西:
this.authService.getProfile().subscribe(profile => {
console.log(profile);
let p = JSON.parse(profile._body)
this.username = p.user.username;
this.email = p.user.email;
})
这将从您的 HTTP 响应
正文中获取 JSON
字符串,并使其成为可访问的对象。
注意:
最好告诉服务器使用标准 json 进行应答,因为这是当今的 Web 标准。
关于javascript - 在 angular2 中使用 HTTP 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48587047/