- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我正在尝试从 apiRoutes.get('/resources/productinfo/:name')
获取一些数据,但出现此错误,我不知道出了什么问题...还有apiRoutes.get('/book/:title')
似乎不起作用!我不知道我做错了什么
更新:
> TypeError: Cannot read property 'findOne' of undefined <br> at Object.module.exports.findBookByTitle
> (/home/themis/firstapp/api/config/database.js:22:26) <br>
> at /home/themis/firstapp/api/server.js:109:22 <br>
> at Layer.handle [as handle_request]
> (/home/themis/firstapp/api/node_modules/express/lib/router/layer.js:82:5)
> <br> at next
> (/home/themis/firstapp/api/node_modules/express/lib/router/route.js:100:13)
> <br> at Route.dispatch
> (/home/themis/firstapp/api/node_modules/express/lib/router/route.js:81:3)
> <br> at Layer.handle [as handle_request]
> (/home/themis/firstapp/api/node_modules/express/lib/router/layer.js:82:5)
> <br> at
> /home/themis/firstapp/api/node_modules/express/lib/router/index.js:234:24
> <br> at param
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:331:14)
> <br> at param
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:347:14)
> <br> at Function.proto.process_params
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:391:3)
> <br> at
> /home/themis/firstapp/api/node_modules/express/lib/router/index.js:228:12
> <br> at Function.match_layer
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:295:3)
> <br> at next
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:189:10)
> <br> at
> /home/themis/firstapp/api/node_modules/express/lib/router/index.js:191:16
> <br> at Function.match_layer
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:295:3)
> <br> at next
> (/home/themis/firstapp/api/node_modules/express/lib/router/index.js:189:10)
这是 server.js
var express = require('express');
MongoClient = require('mongodb').MongoClient,
app = express(),
mongoUrl = 'mongodb://localhost:27017/firstapp';
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var passport = require('passport');
var redisClient = require('redis').createClient;
var redis = redisClient(6379, 'localhost');
var config = require('./config/database'); // get db config file
var User = require('./app/models/user'); // get the mongoose model
var Products = require('./app/models/products'); //get the mongoose model
var Makeissue = require('./app/models/makeissue'); //get the mongoose model
var port = process.env.PORT || 8080;
var jwt = require('jwt-simple');
var access = require('./config/database.js');
MongoClient.connect(mongoUrl, function(err, db) {
if (err) throw 'Error connecting to database - ' + err;
// get our request parameters
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// log to console
app.use(morgan('dev'));
// Use the passport package in our application
app.use(passport.initialize());
// demo Route (GET http://localhost:8080)
app.get('/', function(req, res) {
res.send('The API is at http://localhost:' + port + '/api');
});
// connect to database
mongoose.connect(config.database);
// pass passport for configuration
require('./config/passport')(passport);
// bundle our routes
var apiRoutes = express.Router();
// create a new user account (POST http://localhost:8080/api/signup)
apiRoutes.post('/signup', function(req, res) {
if (!req.body.name || !req.body.password || !req.body.email) {
res.json({success: false, msg: 'Please pass name and password and email.'});
} else {
var newUser = new User({
name: req.body.name,
password: req.body.password,
email: req.body.email
});
// save the user
newUser.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Username already exists.'});
}
res.json({success: true, msg: 'Successful created new user.'});
});
}
});
// route to authenticate a user (POST http://localhost:8080/api/authenticate)
apiRoutes.post('/authenticate', function(req, res) {
User.findOne({
name: req.body.name
}, function(err, user) {
if (err) throw err;
if (!user) {
res.send({success: false, msg: 'Authentication failed. User not found.'});
} else {
// check if password matches
user.comparePassword(req.body.password, function (err, isMatch) {
if (isMatch && !err) {
// if user is found and password is right create a token
var token = jwt.encode(user, config.secret);
// return the information including token as JSON
res.json({success: true, token: 'JWT ' + token});
} else {
res.send({success: false, msg: 'Authentication failed. Wrong password.'});
}
});
}
});
});
apiRoutes.post('/book', function (req, res) {
if (!req.body.title || !req.body.author) res.status(400).send("Please send a title and an author for the book");
else if (!req.body.text) res.status(400).send("Please send some text for the book");
else {
access.saveBook(db, req.body.title, req.body.author, req.body.text, function (err) {
if (err) res.status(500).send("Server error");
else res.status(201).send("Saved");
});
}
});
apiRoutes.get('/book/:title', function (req, res) {
if (!req.param('title')) res.status(400).send("Please send a proper title");
else {
access.findBookByTitle(db, req.param('title'), function (book) {
if (!req.body.text) res.status(500).send("Server error");
else res.status(200).send(book);
});
}
});
apiRoutes.get('/productinfo' , function(req, res, next) {
Products.find( function (err, result) {
if (err) return console.error(err);
res.json(result);
});
});
apiRoutes.get('/resources/productinfo/:name' , function(req, res) {
if (!req.param('name')) res.status(400).send("Please send a proper name");
else{
access.findProductsByName(Products, req.param('name'), function(Products) {
if (!products) res.status(500).send("server error");
});
}
});
// create a new Product (POST http://localhost:8080/api/productsignup)
apiRoutes.post('/resources/productsignup', function(req, res) {
if (!req.body.name || !req.body.serialnumber) {
res.json({success: false, msg: 'Please pass name and serial number.'});
} else {
var newProducts = new Products({
name: req.body.name,
serialnumber: req.body.serialnumber
});
// save the Product
newProducts.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Product already exists.'});
}
res.json({success: true, msg: 'Successful created new Product.'});
});
}
});
apiRoutes.post('/resources/createpost', function(req, res) {
if (!req.body.issue) {
res.json({success: false, msg: 'Please pass a issue.'});
} else {
var newMakeissue = new Makeissue({
issue: req.body.issue
});
// save the Product
newMakeissue.save(function(err) {
if (err) {
return res.json({success: false, msg: 'Post already exists.'});
}
res.json({success: true, msg: 'Successful created new post.'});
});
}
});
// route to a restricted info (GET http://localhost:8080/api/memberinfo)
apiRoutes.get('/memberinfo', passport.authenticate('jwt', { session: false}), function(req, res) {
var token = getToken(req.headers);
if (token) {
var decoded = jwt.decode(token, config.secret);
User.findOne({
name: decoded.name
}, function(err, user) {
if (err) throw err;
if (!user) {
return res.status(403).send({success: false, msg: 'Authentication failed. User not found.'});
} else {
res.json({success: true, msg: 'Welcome in the member area ' + user.name + '!'});
}
});
} else {
return res.status(403).send({success: false, msg: 'No token provided.'});
}
});
getToken = function (headers) {
if (headers && headers.authorization) {
var parted = headers.authorization.split(' ');
if (parted.length === 2) {
return parted[1];
} else {
return null;
}
} else {
return null;
}
};
// connect the api routes under /api/*
app.use('/api', apiRoutes);
module.exports = apiRoutes;
app.listen(8080, function() {
console.log('listening on port 8080');
});
});
和 database.js
module.exports = {
'secret': 'di.ionio.gr',
'database': 'mongodb://localhost/firstapp'
};
module.exports.saveBook = function (db, title, author, text, callback) {
db.collection['text'].save({
title: title,
author: author,
text: text
}, callback);
};
module.exports.findBookByTitle = function (db, title, callback) {
db.collection['text'].findOne({
title: title
}, function (err, doc) {
if (err || !doc) callback(null);
else callback(doc.text);
});
};
module.exports.findProductsByName = function (db, name, callback) {
db.collection['products'].findOne({
name: name
}, function (err, doc) {
if (err || !doc) callback(null);
else callback(doc.products);
});
};
和 package.json
{
"name": "firstapp",
"main": "server.js",
"dependencies": {
"bcrypt": "^0.8.5",
"body-parser": "~1.9.2",
"express": "~4.9.8",
"jwt-simple": "^0.3.1",
"mongoose": "~4.2.4",
"mongodb" : "~1.2.5",
"morgan": "~1.5.0",
"passport": "^0.3.0",
"passport-jwt": "^1.2.1",
"redis": "~0.10.1"
}
}
最佳答案
不正确的语法,你必须阅读 db.collection 的属性,但你调用它。示例:
db.collection['products']!!!
db.collection['text'].save({
title: title,
author: author,
text: text
}, callback);
};
module.exports.findBookByTitle = function (db, title, callback) {
db.collection['text'].findOne({
title: title
}, function (err, doc) {
if (err || !doc) callback(null);
else callback(doc.text);
});
};
module.exports.findProductsByName = function (db, name, callback) {
db.collection['products'].findOne({
例如
变量对象 = { 'some_value':'值(value)', 'some_methid': function(){ 返回 '方法结果'}
您可以读取和设置属性 'some_value',例如:
object['some_value'] // return 'value'
object.some_value // return 'value'
//第二步
好的,在你的 database.js 方法中你传递了 db 变量,但这不是 db 实例,它是 mongoose 模型,你必须这样写:
module.exports.findBookByTitle = function (model, title, callback) {
model.findOne({
title: title
}, function (err, doc) {
if (err || !doc) callback(null);
else callback(doc.text);
});
};
module.exports.findProductsByName = function (model, name, callback) {
model.findOne({
name: name
}, function (err, doc) {
if (err || !doc) callback(null);
else callback(doc.products);
});
};
关于node.js - TypeError : db. 集合不是函数,无法获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34827397/
我正在使用 React Native 构建移动应用程序。我面临 Nativ Base Toast 问题。当我第一次加载应用程序然后导航到工单状态时,如果我返回带有 android 后退按钮的主页,则会
我正在尝试创建一个“完美的滚动条”,它是这样的:。Https://github.com/noraesae/perfect-scrollbar-bower。使用尽可能简单的代码:。我犯了以下错误:。当然
我正在尝试在简单的 Draftjs 编辑器上应用自定义装饰器: import React from 'react'; import {Editor, EditorState, RichUtils} f
读取以钟形字符作为分隔符的CSV文件时,出现类型错误。我不想使用熊猫,我需要使用CSV库来解决这个问题。。示例标题:。数据类型。样本数据:。示例代码。我明白这个错误-。铃声字符参考-https://w
我正在处理 useSelector的 react-redux在我的 React Native 应用程序中,我收到以下错误: TypeError: TypeError: (0, _reactRedux.
当我用 Node 运行以下代码时: var command = "/home/myScript.sh"; fs.exists(command, function(exists){ if(exi
我正在为我的一个组件编写测试用例,该组件具有路由器(使用 withrouter)。我收到错误 wrapper.find is not a function。基本要求是需要检查我的渲染中是否存在标签,还
我一直在研究一个简单的表单提交。首先,我想在提交表单之前创建一个模式警报。于是,我使用了bootstrap的modal函数,反复得到 TypeError: $(...).modal is not a
这个问题在这里已经有了答案: Flask-Login raises TypeError: 'bool' object is not callable when trying to override
这是我在leetcode中遇到的问题。您将看到两个非空链接表,表示两个非负整数。数字以相反的顺序存储,并且它们的每个节点都包含一个数字。将这两个数字相加,然后以链表的形式返回总和。。你可以假设这两个数
我正在尝试学习Python,并试图将GitHub问题变成一种可读的形式。根据关于如何将JSON转换为CSV的建议,我得出了以下结论:。其中“Issues.json”是包含GitHub问题的JSON文件
我在使用 Proxy 类时遇到了这个有趣的错误: TypeError: 'set' on proxy: trap returned truish for property 'users' which
在研究Jupyter笔记本电脑时,我遇到了这个问题:。这是代码开始的地方:。下面的代码是在jupyter笔记本的另一个单元上运行的。我怎么才能解决它呢?。尝试更改参数和一系列其他内容,但所有这些都弹出
Working on jupyter notebooks, I came across this problem:在研究Jupyter笔记本电脑时,我遇到了这个问题: TypeError:un
我对此很陌生(对于 Jasmine 测试、ExtJs 和 JS 来说确实很陌生),我必须修复这个错误/错误。我正在运行一些单元测试,但不断收到以下错误: TypeError: object is no
在下面的文档中,我们可以不使用JupyterDash在笔记本中运行应用程序,而只需运行app.run(jupyter_mode=“外部”)。。Https://dash.plotly.com/dash-
导入地理位置时: import { Geolocation } from '@ionic-native/geolocation/ngx'; 获取错误: ionic Geolocation :Ionic
我定义了以下函数: def eigval(matrix): a = matrix[0, 0] b = matrix[0, 1] c = matrix[1, 0] d =
刚刚获得了SDXL模型的访问权限,希望为即将发布的版本进行测试...不幸的是,我们当前用于我们服务的代码似乎不能与稳定ai/稳定-扩散-xl-base-0.9一起工作,我不完全确定SDXL有什么不同,
这是我的全部代码。我试图通过/insta/:id在我的page.ejs页面上查找,但它显示错误:。无法读取未定义的属性(正在读取‘UserName’)。。我希望获得uuidv4()将提供的id,但它返
我是一名优秀的程序员,十分优秀!