基于express实现商品列表查询接口
2020-05-01 本文已影响0人
是新来的啊强呀
- 安装mongoose
cnpm i mongoose --save
- 创建modules
在server文件夹中创建modules文件夹并定义goods.js文件
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// 定义一个模型
var productSchema = new Schema({
"productId":String,
"productName":String,
"salePrice":Number,
"productImage":String
});
module.exports = mongoose.model('Good',productSchema);
- 启动mongodb数据库
mongod -f /usr/local/etc/mongod.conf
mongod -f /usr/local/etc/mongod.conf --auth // 带权限启动
4.1 在server/app.js中创建goods一级路由
>var goodsRouter = require('./routes/goods');
>app.use('/goods',goodsRouter);
4.2 在server/routers/goods创建二级路由
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Goods = require('../models/goods');
let url= 'mongodb://127.0.0.1:27017/shoppingmall'
mongoose.connect(url,{
useNewUrlParser: true,
useUnifiedTopology: true
});
//mongoose.connect('mongodb://username:password@host:port/database?options...');
mongoose.connection.on("connected",function(){
console.log("MongoDB connected success.");
});
mongoose.connection.on("error",function(){
console.log("MongoDB connected fail.");
});
mongoose.connection.on("disconnected",function(){// mongoose.connect('mongodb://admin:admin@10.211.55.9:27017/shopingmall?authSource=admin'); // 连接MongoDB数据库
console.log("MongoDB connected disconnected.");
});
router.get("/",function(req,res,next){
Goods.find({},function (err,doc) {
if(err){
res.json({
status:"1",
msg:err.mssage
})
}else{
res.json({
status: '0',
msg:'',
result:{
count:doc.length,
list:doc
}
});
}
});
});
module.exports=router;
- 在config/index.js中添加代理
proxyTable: { // 代理插件, 由于端口号为3000跨域了,前端的端口号是8080
'/goods':{
target:'http://localhost:3000'
}
},
- 启动express服务器,启动webpack项目
pm2 start server/bin/www
cnpm run dev
- 运行网页
http://localhost:8080