我的程序正在尝试将数据添加到Heroku上的PostgreSQL数据库,但是当我单击相应的按钮时,它会将数据写为“未定义”。我在调用变量的方式上犯了错误吗?
该应用正在使用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文件,它定义了我试图用角度$ 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();
});
}
};
(这是原版的编辑版本。起初,由于错位的'符号,该功能无效。)
答案 0 :(得分:1)
在addRecord中将其更改为req.query.name
等,而不是req.name
。