我有这样的问题。我正在制作一个平均堆栈应用程序。在该文件中,我创建了一个服务文件来处理预订。它看起来像这样。
import { Injectable } from '@angular/core';
import { HttpClient , HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import {Reservation} from "./reservation";
@Injectable()
export class ReservationService {
public selectedReservation: Reservation = new Reservation();
public reservations: Reservation[];
constructor(private http: HttpClient) { }
getNotConfirmedReservationList(){
return this.http.get('http://localhost:3000/reservation/notComfirmed')
}
confirm(_id: string){
console.log(_id);
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:3000/reservation/confirm', _id, {headers: headers});
}
}
在这里,我已经在控制台日志中正确打印了id。但是在使用Express制作的我的API的Controller文件中,我再次控制日志,它给我的输出为undefined。这里我在API中提供我的Controller文件。
const express = require('express');
var router = express.Router();
var Reservation = require('../models/reservation');
router.post("/create",function (req,res) {
const newReservation = new Reservation({
date: req.body.date,
from: req.body.from,
to: req.body.to,
lab: req.body.lab,
name: req.body.name,
email: req.body.email,
role: req.body.role,
year: req.body.year,
reason: req.body.reason,
state: "Not Comfirm"
});
Reservation.saveReservation(newReservation, function (err, reservation) {
if (reservation) {
res.send(reservation);
}
else {
console.log('Error in User save :' + JSON.stringify(err, undefined, 2));
}
});
});
router.get('/notComfirmed', function (req, res) {
Reservation.findNotComfirmed(function (err, reservations) {
if(err) throw err;
if (!reservations){
res.json({state:false,msg:"No reservations found"});
}
if(reservations){
res.json(reservations);
}
})
});
router.post('/confirm', function(req, res){
const _id= req.body._id;
console.log(req.body._id);
Reservation.updateReservation(_id, function (err, reservation) {
if(err) throw err;
if (!reservation){
res.json({state:false,msg:"Something went wrong"});
}
if(reservation){
res.json(reservation);
}
})
})
module.exports = router;
我多次尝试使用我的代码查找问题。但我无法找到它。有人可以帮我找到这段代码的问题吗?谢谢!
答案 0 :(得分:1)
您没有正确设置请求正文。将from django.db.models import CharField, Case, When
games = Game.objects.all().annotate(
recent_lines=Count(Case(
When(recent_lines__created__gt=date_to_check, then=1),
output_field=CharField())))
替换为return this.http.post('http://localhost:3000/reservation/confirm', _id, {headers: headers});
您没有解析请求正文。将return this.http.post('http://localhost:3000/reservation/confirm', {_id}, {headers: headers});
替换为router.post('/confirm', function(req, res)
并导入router.post('/confirm', json(), function(req, res)
。最后你必须const json = require('body-parser').json
。