Abhishek Parikh Abhishek Parikh - 12 days ago 5
JSON Question

Passing json from Angular JS to Node JS

I am trying to combine my front-end(Angular) and backend(Node) but some how front-end did not pass json to backend

Here is my html code with Angular-js

Index.html

<html>
<head>Testing
<script src = "angular.min.js" ></script>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$http) {
$scope.submit= function(){
var data = $.param({
book: JSON.stringify({
author: $scope.author,
title : $scope.title,
body : $scope.body
})
});
console.log(data)
$http.post("/", data).success(function(data, status) {
console.log('Data posted successfully');
})
}
});
</script>
</head>

<body ng-app="myApp">
<div ng-controller="myCtrl">
<form>
Author:
<input type="text" ng-model="author">
<br>
<br> Title:
<input type="text" ng-model="title">
<br>
<br> Body:
<input type="author" ng-model="body">
<br>
<br>
<input type="submit" value="Submit" ng-click="submit()">
</form>
</div>
</body>
</html>


My node Application is look like below.

Server.js

var express = require('express');
var bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.get('/', function(req, res){
res.sendFile(__dirname +'/index.html');
});

app.post('/', function(req,res,next){
console.log(req.body)
res.status(200).send('Ok')
})

console.log('server running at 3000!')
app.listen(3000);


I am getting Index.html at my browser at'/' route but when i submit nothing is happening.

Thanks in advance

Answer

Can u try this

var data = {
  book: {            
    author: $scope.author,
    title : $scope.title,
    body : $scope.body
  }
}

$http.post("/", data).success(function(data, status) {
    console.log('Data posted successfully');
})
Comments