安装Mongoose
创建model
//server/models/goods.js
var mongoose = require('mongoose');//优先到node_modeles里加载
var Schema = mongoose.Schema;//定义模型
var productSchema = new Schema({
"productId": {type: String},
"productName": String,
"salePrice": Number,
"productImage": String
})
module.exports = mongoose.model('Good', productSchema);//商品模型输出,good默认会加s,去查找goods表
创建路由
//server/routes/goods.js
//二级路由
var express = require('express');//加载express框架
var router = express.Router();
var mongoose = require('mongoose');
var Goods = require('../models/goods');
//基于mongoose,实现查询功能
mongoose.connect('mongodb://127.0.0.1:27017/testMall'); //链接数据库
mongoose.connection.on("connected", function () {
console.log('链接成功');
})
mongoose.connection.on("error", function () {
console.log('链接失败');
})
mongoose.connection.on("disconnected", function () {
console.log('链接断开');
})
router.get('/', function (req, res, next) {
Goods.find({}, function (err, doc) {
if (err) {
res.json({
status: '1',
msg: err.message
});
} else {
res.json({
status: '0',
msg: '',
result: {
count: doc.length,
list: doc
}
})
}
})
})
module.exports = router; //输出
配置路由
//server/app.js
var goods = require('./routes/goods');
app.use('/goods', goods);
设置代理
//config/index.js
proxyTable: {//代理插件
'/goods':{
target:'http://localhost:3000',//访问3000下的/goods
}
},
<wiz_tmp_tag id="wiz-table-range-border" contenteditable="false" style="display: none;">