[英]Only part of the response is retrieved at the ionic 4 front-end
我正在使用令牌將來自ionic的http GET請求發送到NodeJS服務器。 我收到一條消息,提示已成功檢索數據。 但是,當我嘗試將其記錄在控制台中時,響應的數據屬性不會發送到前端,而是分配給undefined。 這是我的離子請求的代碼:
getPoints() {
var headers = new Headers();
headers.append("Authorization", "Bearer " + this.getAuthorizationToken());
headers.append("Content-Type", "application/json");
console.log(this.getAuthorizationToken());
return this.http
.get(environment.apiUrl + "/user/getCurrentPoints", {
headers
})
.map(res => res.json());
}
這是離子組件內部的代碼,我在構造函數中調用GET方法:
constructor(
ease: RoundProgressEase,
private _router: Router,
private formB: FormBuilder,
private _authService: AuthService
) {
for (let prop in ease) {
if (prop.toLowerCase().indexOf("ease") > -1) {
this.animations.push(prop);
}
}
this._authService.getPoints().subscribe((res: any) => {
console.log("data points", res);
});
}
這也是后端的端點:
router.get(
"/user/getCurrentPoints",
isAuthenticated,
userCtrl.getCurrentPoints
);
這是經過身份驗證的中間件:
var isAuthenticated = function(req, res, next) {
var token = req.headers["authorization"];
console.log(req.header);
token = req.headers.authorization.split("Bearer ")[1];
if (!token) {
return res.status(401).json({
error: null,
msg: "You have to login first before you can access your lists.",
data: null
});
}
jwt.verify(token, req.app.get("secret"), function(err, decodedToken) {
if (err) {
return res.status(401).json({
error: err,
msg: "Login timed out, please login again.",
data: null
});
}
req.decodedToken = decodedToken;
console.log(req.decodedToken);
next();
});
};
最后,這是userCtrl.getCurrentPoints
控制器方法:
module.exports.getCurrentPoints = function(req, res, next) {
console.log("accessed get current points");
if (!Validations.isString(req.decodedToken.user.username)) {
return res.status(422).json({
err: null,
msg: "type parameter must be a valid String.",
data: null
});
}
User.find({ username: req.decodedToken.user.username }).exec(function(
err,
user
) {
if (err) {
return next(err);
}
res.status(200).json({
err: null,
msg: "Current user points retrieved successfully.",
data: user.points
});
});
};
這是我得到的回應
{err: null, msg: "Current user points retrieved successfully."}
用戶架構
const mongoose = require('mongoose');
var Voucher = mongoose.Schema.Types.Voucher;
const userSchema = mongoose.Schema({
username: {
type: String,
required: true,
trim: true,
lowercase: true
},
password: {
type: String,
required: true,
trim: true
},
name: {
type: String,
required: true,
trim: true
},
region: {
type: String,
required: true,
trim: true,
},
building: {
type: Number,
required: true,
min: 0
},
points: {
type: Number,
required: false,
min: 0
},
vouchers: {
type: [Voucher],
status:[String],
required: false,
},
createdAt: {
type: Date,
default: Date.now
},
updatedAt: Date
});
mongoose.model('User', userSchema);
您從后端得到什么? 錯誤或數據? 首先檢查您的請求是否獲取后端api。 其次,我看到您檢查了中間件中的小寫授權。 也許那是出問題的地方。 第三,用戶根本沒有任何點,默認情況下,從響應中刪除空字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.