我正在尝试使用Angular在MongoDB中添加新条目。我无法摆脱以下错误消息。有任何想法吗?先感谢您!
(注意:与数据库的连接是正常的。例如,我的get()函数正在工作)
错误消息
C:\Server Files\112-IT-Dep-Equipment-Registering (Back-end)\node_modules\mongodb\lib\utils.js:123
process.nextTick(function() { throw err; });
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
at ServerResponse.header (C:\Server Files\112-IT-Dep-Equipment-Registering (Back-end)\node_modules\express\lib\response.js:725:10)
at ServerResponse.send (C:\Server Files\112-IT-Dep-Equipment-Registering (Back-end)\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (C:\Server Files\112-IT-Dep-Equipment-Registering (Back-end)\node_modules\express\lib\response.js:256:15)
at db.get.collection.insert (C:\Server Files\112-IT-Dep-Equipment-Registering (Back-end)\routes\api.js:22:21)
at C:\Server Files\112-IT-Dep-Equipment-Registering (Back-end)\node_modules\mongodb\lib\collection.js:525:20
at C:\Server Files\112-IT-Dep-Equipment-Registering (Back-end)\node_modules\mongodb\lib\collection.js:659:14
at handleCallback (C:\Server Files\112-IT-Dep-Equipment-Registering (Back-end)\node_modules\mongodb\lib\utils.js:120:56)
at resultHandler (C:\Server Files\112-IT-Dep-Equipment-Registering (Back-end)\node_modules\mongodb\lib\bulk\ordered.js:421:14)
at C:\Server Files\112-IT-Dep-Equipment-Registering (Back-end)\node_modules\mongodb-core\lib\connection\pool.js:461:18
服务器中的API
//----- Add a new entry -----
router.post('/addNewEntry',(req,res,next) => {
var newEntry = req.body;
db.get().collection('data')
.insert(newEntry,(err,data) => {
if (err) { res.send(err) }
res.json({status: 'OK'});
});
});
“入门”课程
export class Entry {
_id: string;
equipment: string;
model: string;
serial: string;
network: string;
ip: string;
description: string;
office: string;
}
entry.service.ts
import { Injectable } from '@angular/core';
import { HttpClient,HttpErrorResponse,HttpHeaders } from '@angular/common/http';
import { throwError } from 'rxjs';
import { catchError,retry } from 'rxjs/operators';
import { Entry } from '../Classes/entry';
const httpoptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
@Injectable()
export class EntryService {
constructor(private http: HttpClient) { }
// ----- Add a new entry -----
addNewEntry(newEntry: Entry) {
return this.http
.post<Entry>('http://192.168.1.5:3000/api/addNewEntry',newEntry,httpoptions)
.pipe(catchError(this.handleError));
}
} // end of Service
app.component.ts
addNewEntry(): void {
this.entryService
.addNewEntry(this.newEntry)
.subscribe(res => {
this.newEntry = { _id: '',equipment: '',model: '',serial: '',network: '',ip: '',description: '',squadron: '',office: '' };
this.success = true;
},err => {
this.errorMsg = err;
this.error = true;
});
}