单击按钮时 "Undefined" 数据正在写入数据库(Angular,正在使用 Jade、Heroku、Node 和 PostgreSQL)

When button is clicked "Undefined" data is being written to the DB (Angular, Jade, Heroku, Node and PostgreSQL are being used)

我的程序试图将数据添加到 Heroku 上的 PostgreSQL 数据库,但是当我单击相应的按钮时,它会将数据写入 "Undefined"。我调用变量的方式有误吗?

该应用正在使用 Node.js。我写入数据库的方法是从 http://www.jitendrazaa.com/blog/webtech/how-to-use-postgresql-in-nodejs/ 复制的,但我使用的是 Jade 而不是 html。

这是显示数据的 Jade 页面,并有一个添加到数据库的按钮。 $scope.addRecord 函数在此处定义:

extends layout

block content
  div(id="container", ng-controller="postgreSQLCtrl")
    h2 Your Business Card's Data
    h3 You can edit any of the fields below. Just click on the field and type whatever you like. To add to the database click the button at the bottom.

    p.lead  Name:
       input(value=name, id="name", maxlength="30", width="600", ng-model="name", type="text")
    p.lead Description: 
      input(value=description, id="description", maxlength="30", width="600", ng-model="description", type="text")
    p.lead Location: 
      input(value=location, id="location", maxlength="30", width="600", ng-model="location", type="text")
    p.lead Company: 
      input(value=company, id="company", maxlength="30", width="600", ng-model="company", type="text")
    p.lead Title: 
      input(value=jtitle, id="jtitle", maxlength="30", width="600", ng-model="jtitle", type="text")
    p.lead URL for Your Photo: 
      input(value=photo, id="photo", maxlength="200", width="600", ng-model="photo", type="text")
    img(src= photo)
    | <button ng-click="addRecord()" id="btnAdd" name="btnAdd" class="btn btn-danger">Add to db</button>

  script(src='//ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js')  
  script.
    var myApp = angular.module('postgreSQL',[ ]);
      myApp.controller('postgreSQLCtrl', ['$scope' ,'$http',  function($scope,$http) {
      $scope.addRecord = function(){
      var url = '/db/addRecord?name='+$scope.name+'&description='+$scope.description+'&location='+$scope.location+'&company='+$scope.company+'&jtitle='+$scope.jtitle+'&photo='+$scope.photo;
      console.log(url);
      $http({method: 'GET', url: '/db/addRecord?name='+$scope.name+'&description='+
      $scope.description+'&location='+$scope.location+'&company='+
      $scope.company+'&jtitle='+$scope.jtitle+'&photo='+$scope.photo}).
      success(function(data, status) {
      alert('Record Added');
      });
      }
      }]);

这是应用程序的主要 js 文件。此代码中有很多与护照有关,可能不相关。

var express = require('express');
var app = express();
var path = require('path');

// Express middleware
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var logger = require('morgan');

// Passport
var passport = require('passport');
var LinkedInStrategy = require('passport-linkedin-oauth2').Strategy;  // source of strategy: https://github.com/auth0/passport-linkedin-oauth2
var config = require('./config.json');
var pg = require('pg');
var http = require('http');
var request = require('request');
var dbOperations = require("./dbOperations.js");
var logFmt = require("logfmt");

// View engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');


// Middleware
app.use(express.static('public')); // Put your static files here
app.use(cookieParser());
app.use(bodyParser());
app.use(session({ secret: 'shhhsupersecret' }));
app.use(passport.initialize());
app.use(passport.session());

// Logger
app.use(logger('dev'));


// heroku tells us to use this 
/*
pg.connect(process.env.DATABASE_URL, function(err, client) {
  if (err) throw err;
  console.log('Connected to postgres! Getting schemas...');

  client
    .query('SELECT table_schema,table_name FROM information_schema.tables;')
    .on('row', function(row) {
      console.log(JSON.stringify(row));
    });
});
*/

// Passport session setup.
// to support persistent login sessions, passport needs to be able to
// serialize users into and deserialize users out of the session.  Typically,
// this will be as simple as storing the user ID when serializing, and finding
// the user by ID when deserializing.  However, since this example does not
// have a database of user records, the complete LinkedIn profile is
// serialized and deserialized.
passport.serializeUser(function(user, done) {
  done(null, user);
});

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

passport.use(new LinkedInStrategy({
  clientID: config.LINKED_IN_CLIENT_ID,  
  clientSecret: config.LINKED_IN_CLIENT_SECRET,
  callbackURL: "http://shrouded-reef-9087.herokuapp.com/auth/linkedin/callback",
  scope: [ 'r_basicprofile' ],
  passReqToCallback: true
}, function(req, accessToken, refreshToken, profile, done) {
  // asynchronous verification, for effect... 
  req.session.accessToken = accessToken;
  process.nextTick(function () {
    // To keep the example simple, the user's LinkedIn profile is returned to 
    // represent the logged-in user. In a typical application, you would want 
    // to associate the LinkedIn account with a user record in your database, 
    // and return that user instead. 
    done(null, profile);
  });
}));

// Routes
app.get('/', function (req, res) {
  res.render('index', {title: 'LinkedIn Test Authorization'});
});

/*
from http://www.jitendrazaa.com/blog/webtech/how-to-use-postgresql-in-nodejs/

app.get('/' , function(req,res) {
    res.sendfile('views/index.html');
} );
*/
app.get('/db/readRecords', function(req,res){
    dbOperations.getRecords(req,res);
});
app.get('/db/addRecord', function(req,res){
    dbOperations.addRecord(req,res);
});
app.get('/db/delRecord', function(req,res){
    dbOperations.delRecord(req,res);
});
app.get('/db/createTable', function(req,res){
    dbOperations.createTable(req,res);
});
app.get('/db/dropTable', function(req,res){
    dbOperations.dropTable(req,res);
}); 

app.get('/user', function(req, res) {
  console.log('User Object: ', req.user);
  var name = req.user.displayName;
  var description = req.user._json.headline;
  var location = req.user._json.location.name;
  var company = req.user._json.positions.values[0].company.name;
  var jtitle = req.user._json.positions.values[0].title;
  var photo = req.user.photos[0];
  console.log('-----Desired data:  ',name,description,location,company,jtitle,photo);
  console.log('-----Desired data length:  ',name.length,description.length,location.length,company.length,jtitle.length,photo.length);
  res.render('user', {name: name, description: description, location: location, company: company, jtitle: jtitle, photo: photo, title: 'Your Business Card'});
});

// This sends the user to authenticate with linked-in
app.get('/auth/linkedin',
  passport.authenticate('linkedin', { state: 'asdfqwertlkjhz91xcv' }),
  function(req, res){
  // The request will be redirected to LinkedIn for authentication, so this 
  // function will not be called. 
});

// This is where we handle the callback and redirect the user
app.get('/auth/linkedin/callback', 
  passport.authenticate('linkedin', { failureRedirect: '/' }),
  function (req,res) {

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

// The server
var server = app.listen(process.env.PORT || 3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('LinkedIn Test app listening at http://%s:%s', host, port);
});

这是 dbOperations.js 文件,它定义了我试图用 angular $scope.addRecord 函数调用的 "addRecord" 函数。

module.exports = {
  getRecords: function(req, res) {    
        var pg = require('pg');        
        //You can run command "heroku config" to see what is Database URL from Heroku belt
        var conString = process.env.DATABASE_URL || "postgres://postgres:Welcome123@localhost:5432/postgres";
        var client = new pg.Client(conString);
        client.connect();
        var query = client.query("select * from cards");
        query.on("row", function (row, result) { 
            result.addRow(row); 
        });
        query.on("end", function (result) {          
            client.end();
            res.writeHead(200, {'Content-Type': 'text/plain'});
            res.write(JSON.stringify(result.rows, null, "    ") + "\n");
            res.end();  
        });
  },
    addRecord : function(req, res){
        var pg = require('pg');          
        console.log("--------------req=",req);
        var conString = process.env.DATABASE_URL ||  "postgres://postgres:Welcome123@localhost:5432/postgres";
        var client = new pg.Client(conString);
        client.connect();
        var query = client.query("insert into cards (name,description,location,company,jtitle,photo) "+ 
                                "values ('"+req.name+"','"+req.description+"','"+
                                    req.location+"','"+req.company+
                                    "','"+req.jtitle+"','"+req.photo+
                                    "')");    
        query.on("end", function (result) {          
            client.end(); 
            res.write('Success');
            res.end();  
        });
    },    
     delRecord : function(req, res){
        var pg = require('pg');           
        var conString = process.env.DATABASE_URL ||  "postgres://postgres:Welcome123@localhost:5432/postgres";
        var client = new pg.Client(conString);
        client.connect();         
        var query = client.query( "Delete from cards Where id ="+req.query.id);    
        query.on("end", function (result) {          
            client.end(); 
            res.write('Success');
            res.end();  
        });
    },    
    createTable : function(req, res){
        var pg = require('pg');
        var conString = process.env.DATABASE_URL ||  "postgres://postgres:Welcome123@localhost:5432/postgres";
        var client = new pg.Client(conString);
        client.connect();         
        var query = client.query( "CREATE TABLE cards"+
                                    "("+
                                      "name character varying(50),"+
                                      "description character varying(50),"+
                                      "location character varying(50),"+
                                      "company character varying(50),"+
                                      "jtitle character varying(50),"+
                                      "photo character varying(200),"+
                                      "id serial NOT NULL"+
                                    ")");    
        query.on("end", function (result) {          
            client.end(); 
            res.write('Table Schema Created');
            res.end();  
        });
    },    
    dropTable : function(req, res){
        var pg = require('pg');           
        var conString = process.env.DATABASE_URL || "postgres://postgres:Welcome123@localhost:5432/postgres";
        var client = new pg.Client(conString);
        client.connect();         
        var query = client.query( "Drop TABLE cards");    
        query.on("end", function (result) {          
            client.end(); 
            res.write('Table Schema Deleted');
            res.end();  
        });
    }    
};

(这是原始版本的编辑版本。起初,由于 ' 符号放错位置,该功能无法正常工作。)

在 addRecord 中将其更改为 req.query.name 等,而不是 req.name