我有这样的问题。我正在做一个卑鄙的堆栈应用程序。在该文件中,我创建了一个服务文件来处理预订。看起来像这样。
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文件中,我再次控制台记录了ID的ID,该ID给了我未定义的输出。在这里,我在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;
我尝试了很多次才发现我的代码有问题。但是我找不到它。有人可以帮助我找到此代码的问题吗?谢谢!
您没有正确设置请求正文。替换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
。最终你不得不npm i --save body-parser
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句