Reputation: 766
Usign Angular 5 Nodejs and Multer I am trying to upload the file so first i am trying to get the file to some directory and then that path has to be inserted to the db, so first i created the form
<input type="file" (change)="onFileSelected($event)">
<button type="button" (click)="onUpload()">Upload</button>
After that i have the functions in my .ts files
onFileSelected(event){
this.selectedFile = event.target.files[0];
}
onUpload(){
var fd = new FormData();
fd.append('productImage', this.selectedFile, this.selectedFile.name);
this.httpClient.post('http://localhost:3000/uploadImage/1', fd )
.subscribe(res => {
console.log(res);
});
}
my node rest call is as follows
app.post('/uploadImage/:id', upload.single("productImage") ,(request, result) => {
result.send(request.file);
result.send(request.params.id);
result.send("Done");
});
the part where i am confused is since i am setting the header at the node side how do i remove it from the front end to avoid the following error that says can't set headers when they are sent
Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:494:11)
at ServerResponse.setHeader (_http_outgoing.js:501:3)
at ServerResponse.header (D:\Projects\Craiglist\api\node_modules\express\lib\response.js:767:10)
at ServerResponse.contentType (D:\Projects\Craiglist\api\node_modules\express\lib\response.js:595:15)
at ServerResponse.send (D:\Projects\Craiglist\api\node_modules\express\lib\response.js:145:14)
at app.post (D:\Projects\Craiglist\api\index.js:41:12)
at Layer.handle [as handle_request] (D:\Projects\Craiglist\api\node_modules\express\lib\router\layer.js:95:5)
at next (D:\Projects\Craiglist\api\node_modules\express\lib\router\route.js:137:13)
at Array.<anonymous> (D:\Projects\Craiglist\api\node_modules\multer\lib\make-middleware.js:53:37)
at listener (D:\Projects\Craiglist\api\node_modules\on-finished\index.js:169:15)
Upvotes: 1
Views: 757
Reputation: 341
you can use result.send function only once in each route. your code should become something like this:
app.post('/uploadImage/:id', upload.single("productImage") ,(request, result) => {
finalResult = {
requestFile: request.file,
requestParams: request.params.id,
message: "Done!"
};
result.send(finalResult);
});
Upvotes: 1