简体   繁体   中英

Angular Form Submit Post to Database

I am trying to post my form data to my database. When I click the submit button nothing happens. It should be calling my addDiscovery method in the discoverCtrl, but it just does nothing. I am getting no errors and have watched several tutorials in which (to me) I don't see the difference in my code and what is presented. Please tell this Angular noob what he is doing wrong!...Thanks in advance.

discoverCtrl.js:

angular.module('app')
.controller('discoverCtrl', ['$scope', '$http', function($scope, $http, $log) {
    $scope.title = "Discover It!";

    $scope.objects = ['animal', 'art', 'food', 'landform', 'object', 'plant', 'pokemon', 'vehicle'];

    this.discovery = {};

    $scope.addDiscovery = function() {
        this.discovery.image = "";
        this.discovery.location = ""/*gps api call*/;
        this.discovery.discoveredOn = Date.now();
        console.log("I'm posting something maybe?");
        $http.post('/discover', {discovery: this.discovery}).success(function(data) {

        });
        this.discovery = {};
    };
}]);

discover.html:

<h1>{{title}}</h1>

<form name="discoverForm" ng-controller="discoverCtrl" ng-submit="discoverForm.$valid && discoverCtrl.addDiscovery" novalidate>

<input ng-model="discoverCtrl.discovery.name" type="text" class="form-control" placeholder="What is the name of your discovery?" title="name" required />

<select ng-model="discoverCtrl.discovery.objectType" class="form-control" ng-options="object for object in objects" title="objectType" required>
    <option value="" disabled selected>Select what type of discovery you have found.</option>
</select>

<textarea ng-model="discoverCtrl.discovery.description" class="form-control" placeholder="What does your discovery look/feel/smell like? Are there any other observations or knowledge you can share about it?" title="description" required></textarea>

<!--location found by gps TODO-->

<div>Discovery is {{discoverForm.$valid}}</div>
<input type="submit" ng-click="discoverCtrl.addDiscovery" class="btn btn-primary pull-right" value="Discover It!" />

</form>

server.js (sorry for the length. The route is at the bottom, but I didn't know if it could have been something else in here as well so I wanted to include it.):

// requires express and body-parser
var express = require('express');
var bodyParser = require('body-parser');
var expressSessions = require('express-session');
var logger = require('morgan');
var passport = require('passport');

// Google oauth2 login, key, and secrets
var GoogleStrategy = require('passport-google-oauth20').Strategy;
var configAuth = require('./auth');

// OAuth 2.0-based strategies require a `verify` function which receives the
// credential (`accessToken`) for accessing the Facebook API on the user's
// behalf, along with the user's profile.  The function must invoke `cb`
// with a user object, which will be set at `req.user` in route handlers after
// authentication.
passport.use(new GoogleStrategy(configAuth.googleAuth,
  function(accessToken, refreshToken, profile, cb) {
    console.log('access token is', accessToken)

    return cb(null, profile);
  }));

// Configure Passport authenticated session persistence.
//
// In order to restore authentication state across HTTP requests, Passport needs
// to serialize users into and deserialize users out of the session.  In a
// production-quality application, this would typically be as simple as
// supplying the user ID when serializing, and querying the user record by ID
// from the database when deserializing.  
passport.serializeUser(function(user, cb) {
  cb(null, user);
});

passport.deserializeUser(function(obj, cb) {
  cb(null, obj);
});

//requiring and setting up mongo database/collections
var mongojs = require('mongojs');
var databaseUrl = "discoverIt";
var collections = ["users", "discoveries"];

// creates a databse in mongo called scrape with two collections: articles and comments
var db = mongojs('discoverIt', ['users', 'discoveries']);

// lets us know if there is an error with the database if it doesn't turn on
db.on('error', function(err) {
    console.log('Database Error: ', err);
});

// creating an instance of express
var app = express();

// assigning the port or using the PORT environment variable
var PORT = process.env.PORT || 3000; 

// makes static content in assets accessible
app.use(express.static(__dirname + '/public')); 

// // BodyParser interprets data sent to the server
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.text());
app.use(bodyParser.json({type: 'application/vnd.api+json'}));

// Use application-level middleware for common functionality, including
// logging, parsing, and session handling.
app.use(require('morgan')('combined'));
app.use(require('cookie-parser')());
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('express-session')({ secret: 'keyboard cat', resave: true, saveUninitialized: true }));

// Initialize Passport and restore authentication state, if any, from the
// session.
app.use(passport.initialize());
app.use(passport.session());

// Define routes.
app.get('/',  function(req, res) {

    res.sendFile(__dirname + '/public/views/index.html');
  });

app.get('/login',
  function(req, res){

    res.sendFile(__dirname + '/public/views/login.html');
  });

app.get('/login/google',
  passport.authenticate('google', {scope: 'profile'}));

app.get('/login/google/return', 
  passport.authenticate('google', { failureRedirect: '/login' }),
  function(req, res) {

    res.redirect('/profile');
  });

app.get('/profile',
  require('connect-ensure-login').ensureLoggedIn(),
  function(req, res){


      db.users.insert({
        "email": "",
        "avatar": req.user.photos[0].value,
        "userName": req.user.displayName,
        "discoveries": 0,
        "edits": 0,
        "confirms": 0,
        "points": 0
      });

      res.send({ user: req.user });
  });

  app.post('/discover', function(req, res){

      db.discoveries.insert({
        "user": req.user.displayName,
        "userId": req.user.id,
        "image": req.body.discovery.discovery.image,
        "name": req.body.discovery.discovery.name,
        "objectType": req.body.discovery.discovery.objectType,
        "description": req.body.discovery.discovery.description,
        "location": req.body.discovery.discovery.location,
        "discoveredOn": req.body.discovery.discovery.discoveredOn
      });

//*********************************
     //increase user discovery count
//**********************************


  });

//******************************************************



//starts the server letting user know the PORT
app.listen(PORT, function(){

    console.log("listening on port %d", PORT);

}); // end of app.listen

正如@dustmouse所说,我需要()... oops!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM