Reputation: 3932
I'm trying so send some json data from angularjs to express/nodejs
AngularJS code:
$http({
method: 'POST',
url: 'http://localhost:8000/api/auth',
data: {
name: user,
password: passwd
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function(data, status, headers, config) {
$scope.loginStatus = data;
})
.error(function(data, status, headers, config) {
$scope.lloginStatusogin = data;
});
ExpressJS code:
var express = require('express');
var app = express();
var config = require('./config'); // get our config file
var port = process.env.PORT || 8000; // used to create, sign, and verify tokens
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
var apiRoutes = express.Router();
apiRoutes.post('/auth', function(req, res) {
console.log(req.body)
});
app.use('/api', apiRoutes);
app.listen(port);
but at express when log the req.body
i get this object
{ '{"name":"Nick","password":"password"}': '' }
the whole json object is taken as a property having an empty value i don't understand or see what am doing wrong.
Upvotes: 1
Views: 73
Reputation: 18392
Send Content-Type: application/json
if you try to send an object. application/x-www-form-urlencoded
expects an urlEncoded string as body property. The following both solutions should work for you, choose one.
application/json
content-type$http({
method : 'POST',
url : 'http://localhost:8000/api/auth',
data : {
name: user,
password: passwd
},
headers : {'Content-Type': 'application/json'}
})
.success(function(data, status, headers, config){
$scope.loginStatus=data;
})
.error(function(data, status, headers, config){
$scope.lloginStatusogin=data;
});
application/x-www-form-urlencoded
content-type.transformRequest
will create a urlEncoded string based on data
before the request will be send.
$http({
method: 'POST',
url: 'http://localhost:8000/api/auth',
transformRequest: function(obj) {
var str = [];
for(var p in obj) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
},
data: {
name: user,
password: passwd
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data, status, headers, config){
$scope.loginStatus=data;
})
.error(function(data, status, headers, config){
$scope.lloginStatusogin=data;
});
Upvotes: 1
Reputation: 15292
In the header part : it should be
{'Content-Type': 'application/json'}
instead of
{'Content-Type': 'application/x-www-form-urlencoded'}
Upvotes: 1