Jan sebastian Jan sebastian - 3 months ago 28
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

script.js

$scope.save1 =function()
{
var input2 = {
"_id":$scope.iduser,
"Name":$scope.username,
"position":$scope.position,
"level":$scope.level,
"acclevel":$scope.data.acclevel,
"status":$scope.status1,
"pass":$scope.pass
}
$http.post("http://localhost:22345/user",input2)
.success(function(res) {
if(res.error == 0)
{
$scope.status1 = "active";
$scope.iduser = "";
$scope.username = "";
$scope.position = "";
$scope.level = "";
$scope.data.acclevel = "";
$scope.pass = "";
$scope.IdUser = false;
alert("save success");
}
else
{
console.log(res.User);
}
});
} }]);


my rest API (user.js)

app.post("/user",function(req,res){

var users = new user(req.body);
users.save(function(err,users){
if(err)
{
data['error'] = 1;
data['User'] = err;
res.json(data);
}
else
{
data['error'] = 0;
res.json(data);
}
})
});


models

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

update

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-Origin","*");
res.header('Access-Control-Allow-Methods','POST,GET,PUT,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers","X-Requested-With,X-HTTP-Methods-Override,Content-Type,Accept,Cache-Control, Pragma, Origin,Authorization, Content-Type");
res.header("Access-Control-Allow-Credentials","true");
if ('OPTIONS' == req.method){
return res.send(200);
}
next();
});


so thanks for all answers

Answer

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 w3.org 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 w3.org 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.