Reputation: 137
I have an Angular frontend which takes id and password for a login form,then I POST this value to a node.js server and from this server I send a JSON object back to Angular.
All works fine except the reading of this object from Angular. I think I've done the right steps, but the console shows me "undefined" as if it does not recognize the format.
I'm new with node and this is just an example to try to catch the response from node.
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.post('/login',function(req,res){
console.log("sono nella post "+req.body.username);
res.setHeader('Content-Type', 'application/json');
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Credentials", true);
res.json({ack:'ok'});
});
app.listen(9080,function(){
console.log('Server running at http://127.0.0.1:9080/');
});
var app = angular.module('myApp',[]);
app.controller('myCtrl',function($scope,$http){
$scope.check = function(data) {
var id = data.form.id;
var pwd = data.form.password;
console.log("utente è "+id+",password è "+pwd);
var msg = {username: id,password: pwd};
$http({
// without anything here, put * in app.post()
url : 'http://localhost:9080/login',
method : "POST",
data : $.param(msg),
responseType : "application/json",
headers : {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(response) {
console.log("Server response "+response.ack);
});
};
});
When running this, the console shows me Server response undefined
.
Thanks in advance for the help.
Upvotes: 0
Views: 2974
Reputation: 885
try with
console.log("Server response "+ response.data);
instead of
console.log("Server response "+response.ack);
Upvotes: 1
Reputation: 4269
According to the Angular $http
documentation:
The response object has these properties:
- data – {string|Object} – The response body transformed with the transform functions.
- status – {number} – HTTP status code of the response.
- headers – {function([headerName])} – Header getter function.
- config – {Object} – The configuration object that was used to generate the request.
- statusText – {string} – HTTP status text of the response.
So, if you try response.data.ack
, then it might work.
Upvotes: 3