Reputation: 73
I basically need to save a formData on a mongodb schema, using nodejs + express as backend, and multer as middleware, this formData consist on a string and a blob
i need to capture the blob and the string and somehow save on the db, but right now i cant even capture on my backend
my req.body and my req.files appear as undefined
thanks in advance
Post Service on angular
addPost(message, blob): Observable<any> {
var fd = new FormData();
fd.append('id', message);
fd.append('invoiceFile', blob);
let httpHeaders = new HttpHeaders({
Accept: 'multipart/form-data'
});
let options = {
headers: httpHeaders
};
return this.http.post(`${addPost}`, fd, options);
}
My node server.js
const express = require('express');
const mongoose = require('mongoose');
const cookieParser = require('cookie-parser');
// const morgan = require('morgan');
const app = express();
const cors = require('cors');
var fs = require('fs');
const dbConfig = require('./config/env');
app.options('*', cors());
app.use(cors({ credentials: true, origin: true }));
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Credentials', 'true');
res.header('Access-Control-Allow-Methods', 'GET', 'POST', 'DELETE', 'PUT');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept'
);
next();
});
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ extended: true, limit: '50mb' }));
app.use(logger('dev'));
mongoose.Promise = global.Promise;
mongoose.connect(
dbConfig.url,
{ useNewUrlParser: true }
);
const auth = require('./routes/authRoutes');
const posts = require('./routes/postRoutes');
app.use(cookieParser());
app.use(auth);
app.use(posts);
app.listen(3000, () => {
console.log('Runnning on port 3000');
});
My route
router.post('/api/post/add-post', upload.any(), function(req, res) {
console.log(req.body); // appear as undefined
console.log(req.file); // appear as undefined
res.status(204).end();
});
Upvotes: 1
Views: 578
Reputation: 61
Try checking if while sending your form Data is blank or not .
It should be in jpg/jpeg or the format you want to send. I had my form data blank so i realized i had to send file.name which is "image.jpg" and not the entire file details
send a snapshot below see if this helps
Upvotes: 1