Tuesday 9 May 2017

Can not able to store data on mongoDB with Angular,js and Node,js

I am learning the MEAN stack. As I was trying to execute the basic program where I am storing HTML form data mongoDB by using Angular.js and node.js. But I am getting error and I am not able solve it.

console output:

clicked submit

index.html:1 XMLHttpRequest cannot load http://localhost:8080/blah. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

angular.min.js:123 Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"http://localhost:8080/blah","data":{},"headers":{"Accept":"application/json, text/plain, /","Content-Type":"application/json;charset=utf-8"}},"statusText":""}

I am posting code of html file, angular js file and node.js file

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  <script src="Scripts/angular.min.js"></script>
  <script src="Scripts/app.js"></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>

app.js

var app = angular.module('myApp', []);
 app.controller('myCtrl', function($scope,$http) {
 $scope.data = {};
$scope.submit= function(){
    console.log('clicked submit');
    $http({
        url: 'http://localhost:8080/blah',
        method: 'POST',
        data: $scope.data
    }).then(function (httpResponse) {
        console.log('response:', httpResponse);
    })
   }
 });

server.js

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

mongoose.connect('mongodb://localhost/loginapp');
var db = mongoose.connection;


//const url = 'mongodb://localhost:27017/conFusion';

var port = 8080;

var app = express();

app.use(bodyParser.json({limit: '50mb'}));
app.use(express.static('public'));

app.post('/blah', function(req, res, next){
  var cope = req.body.params;
  db.collection('book').insert(cope, (err, result) => {
    if (err) 
    { 
      res.send({ 'error': 'An error has occurred' }); 
    } 
    else 
    {
      res.send(result.ops[0]);
    }

  });
});

app.listen(port, () => {
  console.log('We are live on ' + port);
});  



via Jay Tanna

No comments:

Post a Comment