我在执行POST请求时发送查询参数。我尝试使用req.query.mmCode,它在服务器端不断返回未定义。
app.js
app.post("/api/risk/:id", (req, res) => {
// Create a new note and pass the req.body to the entry
var mmCode = req.query.mmCode;
console.log(mmCode);
服务
addRisk(params: HttpParams, id: string) {
console.log(params);
this.http
.post("http://localhost:3000/api/risk/" + id, { params })
.subscribe(responseData => {
console.log(responseData);
// this.vehicles.push(vehicle);
// this.vehicleUpdate.next([...this.vehicles]);
});
}
add.component.ts
onAddVehicle(form: NgForm) {
this.params = null;
if (form.invalid) {
return;
}
this.isLoading = true;
const vehicle: Vehicle = { id: null, mmCode: form.value.mmCode, vehicleType: form.value.vehicleType,
make: form.value.make, model: form.value.model, regYear: form.value.regYear};
this.http.post<{ message: string, vehicle: Vehicle }>("http://localhost:3000/api/vehicles", vehicle)
.subscribe((responseData) =>{
this.addVehicle = responseData;
this.addMMCode = this.addVehicle.vehicle.mmCode;
this.vehicleID = this.addVehicle.vehicle._id;
this.params = new HttpParams()
.set('mmCode', this.addMMCode);
console.log('CODE ' + this.addMMCode);
this.vehicleService.addRisk(this.params, this.vehicleID);
this.isLoading = false;
form.resetForm();
}
您无法检索POST查询参数的原因是因为没有任何参数。HttpClient
的post()
大致定义如下:post(url, requestBody, options)
。查询参数应以options
而不是形式传递body
。因此,在您的示例(service.ts
)中:
addRisk(params: HttpParams, id: string) {
this.http
.post("http://localhost:3000/api/risk/" + id, { params })
.subscribe(responseData => {
console.log(responseData);
});
}
应该
addRisk(params: HttpParams, id: string) {
this.http
.post("http://localhost:3000/api/risk/" + id, null, { params })
.subscribe(responseData => {
console.log(responseData);
});
}
HttpClient的文档:参考
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句