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.
My server-side JS (Node.js) :
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/');
});
My client-side JS (Angular) :
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.
response, add a breakpoint and do the same, or console.log(response) directly. That likely would have solved the problem for you without you having to spend your time and our time here.