我尝试使用 Angular 8 中的 http post 请求获取完整请求。但是我无法从前端获得完整响应。是这样的,
{"classname": "2A"}
但我尝试使用 postman 检查后端。它给了我正确的响应,如下所示,
{
"stuPosition": 2,
"stuAverage": "80.0000",
"classname": "2A"
}
这是我的 .ts 代码
async classStudentData() {
const Studata = {
term: this.DataForm1.value.term,
classname: this.DataForm1.value.className,
year: this.DataForm1.value.year,
userid: this.userid
};
const url = 'http://localhost:3000/student_marks/studentAverage'
this.http.post<any>(url, Studata).subscribe(res => {
console.log(res)
})
}
server.js 文件 当我从前端发送请求时,后端有 colsole.log() StuAverage,它是未定义。但 postman 请求并不是未定义的。
router.post("/studentAverage", function (req, res) {
const year = req.body.year
const term = req.body.term
const userid = req.body.userid
const classname = req.body.classname
console.log(typeof(term))
console.log(year + " " + term + " " + userid + " " + classname);
var stuPosition;
var stuAverage;
var arr1 = new Array();
mark.aggregate([
{
$match: { "year": year, "term": term, "classname": classname }
},
{
$unwind: "$marks"
},
{
$group: {
_id: "$marks.userid",
avg: { $avg: { $toInt: "$marks.mark" } },
}
}
])
.sort({ _id: 1 })
.exec()
.then(function (resp) {
var i = 0;
for (i = 0; i < resp.length; i++) {
arr1.push(resp[i])
}
var j = 0
for (j = 0; j < arr1.length; j++) {
if (arr1[j]._id == userid) {
stuPosition = j + 1
stuAverage = Math.floor(arr1[j].avg).toFixed(4)
}
}
const avg = stuAverage
console.log(avg)
res.send({
stuPosition: stuPosition,
stuAverage: avg,
classname: classname
})
});
})
最佳答案
这里我检查了后端请求值的数据类型,它们是数字和字符串,再次检查了postman请求,它们都是String类型。因此,我将代码中的所有值转换为字符串,如下所示。
const year = req.body.year.toString()
const term = req.body.term.toString()
const userid = req.body.userid.toString()
const classname = req.body.classname.toString()
现在代码可以正常工作了。感谢所有支持我的人。
关于node.js - Angular HTTP 无法获得完整响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59973965/