view raw
Jan sebastian Jan sebastian - 8 months ago 50
Node.js Question

mongoose, post data using form-data

so I wan,t to post data from web form to database
and this is all of my code


$scope.save1 =function()
var input2 = {
.success(function(res) {
if(res.error == 0)
$scope.status1 = "active";
$scope.iduser = "";
$scope.username = "";
$scope.position = "";
$scope.level = "";
$ = "";
$scope.pass = "";
$scope.IdUser = false;
alert("save success");
} }]);

my rest API (user.js)"/user",function(req,res){

var users = new user(req.body);,users){
data['error'] = 1;
data['User'] = err;
data['error'] = 0;


var mongoose = require("mongoose");
var Schema = mongoose.Schema;

var user = new Schema({
_id : String,
Name : String,
position : String,
level : String,
status : String,
pass : String},{ collection: 'user'});
var user = mongoose.model("user",user);
module.exports.user = user;

when i try to post using postman using form-data, i always get an error result but if i use x-www-form-urlencoded, i can get success result, so whats the problem from mya code. thank you


finaly I found the problem, it's happend when I try to crate header (Access-Control-Allow-Origin,Access-Control-Allow-Methods,etc) co I change it with this

app.use(function (req,res,next) {
res.header("Access-Control-Allow-Headers","X-Requested-With,X-HTTP-Methods-Override,Content-Type,Accept,Cache-Control, Pragma, Origin,Authorization, Content-Type");
if ('OPTIONS' == req.method){
return res.send(200);

so thanks for all answers


Form-data and x-www-form-urlencoded are different type of form content type defined by W3C.

x-www-form-urlencoded is Default, it is used to send simple text/ASCII data.

Form-data is used when you have non-ASCII data or large Binary data.

According to the documentation:

The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

In your case, you have simple text/ASCII data. Thus, x-www-form-urlencoded will work instead of form-data.

Read Documentation on Form Content Types by for better understanding of these form content types.

you can also refer to Postman Docs to clear your doubts.

I hope this clears your doubt.