I recently created an API that accepts files. I am trying to test the API using Postman. If I make a post request using x-wwww-form-urlencoded
body type, everything works and I get all the expected data. The only problem is that it does not allow to send a file. If I use form-data
body type, that allows you to send files, I don't receive anything at the back-end. Not sure if something is wrong with Postman or if I am doing something wrong. My hunch is that the back-end doesn't accept form-data
currently, that is why I am not receiving any data. Anything I could do to change that?
My headers look something like this so far,
res.setHeader('Access-Control-Allow-Origin', origin);
res.header("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, form-data");
app.js
app
// static route will go to the client (angular app)
.use(express.static('client'))
// secured routes
.use('/api', secured_route)
// add a user route
.post('/user', user_api_controller.add_user)
// delete this in the production
.use(function(req, res, next) {
res = allowed_orgins(req, res);
next();
})
;
allowed_orgins = function (req, res){
var allowedOrigins = ['http://localhost:4200', 'http://localhost:8100'];
var origin = req.headers.origin;
if(allowedOrigins.indexOf(origin) > -1){
res.setHeader('Access-Control-Allow-Origin', origin);
res.header("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, multipart/form-data");
}
return res;
}
user_api_controller.js
module.exports.add_user = function (req, res) {
console.log(req.body.username);
console.log(req.body.other_parameters);
}
I get nothing print out on console if I use form-data
, but it works fine when I use x-wwww-form-urlencoded
.
I've used multer middle ware
, I am still not getting anything. Middle ware comes into play when my back-end will receive something. I have tried getting the plain text fields of form-data
, and I am not getting that either. That means my back-end is unable to receive all form-data
fields, not just files but the text fields as well.