这是一个仿网易云音乐的移动应用后端工程说明。
(网易云有登录注册等的接口,但是由于没有做过移动端的应用,对于express和mongoDB都不熟悉,所以没有用接口,直接自己写了个后端来实践一些交互操作,目前还是大三,对于优化之类的都不大熟悉,文件仅供参考,欢迎讨论指正。)
本工程github链接
前端工程github链接
前端工程博客链接
技术栈
- express:node.js的后端框架
- MongoDB:数据库
工程目录
工程配置步骤
安装express
cnpm i express --S
安装mongoose
cnpm i mongoose -S
编写Scheme举例
var mongoose = require('./db.js');//连接数据库
var Schema = mongoose.Schema;
var listCollectionSchema = new Schema({//新建Schema对象
username: { type: String },//用户名
listid:{type:Number}//歌单id
});
/*抛出model*/
module.exports = mongoose.model('ListCollection', listCollectionSchema);
数据增删改查api举例
收藏歌单(增)
router.post("/addListCollection",function(req,res,next){
//新建ListCollectionInfo对象
var listCollectionInfo = new ListCollectionInfo({
//从前端获取数据
username:req.body["username"],
listid:req.body["listid"]
});
//查找歌单id,查看是否已收藏过,不重复收藏
//用的findOne
ListCollectionInfo.findOne({listid: listCollectionInfo.listid}, function (err, data) {
if (!data) {
ListCollectionInfo.create(listCollectionInfo, function (err, data) {
listCollectionInfo.save(function (err,result) {
if(err){
console.log(err);
}else{
//返回json数据给前台
res.json({
message:"收藏歌单成功"
})
}
})
})
} else {
res.json({
message:"收藏歌单失败"
})
}
});
});
取消收藏歌单(删)
router.post("/deleteListCollection",function(req,res,next){
var listCollectionInfo = new ListCollectionInfo({
username:req.body["username"],
listid:req.body["listid"]
});
//其他的与上例类似,区别在于用deleteOne
ListCollectionInfo.deleteOne({username: listCollectionInfo.username,listid:listCollectionInfo.listid},function (err, data) {
if (data) {
res.json({
message:"取消收藏成功"
})
} else {
res.json({
message:"取消收藏失败"
})
}
});
});
修改密码(改)
router.post("/edit",function(req,res,next){
var userinfo = new User({
username:req.body["username"],
userpwd:req.body["newpwd"],
userpwdConfirm:req.body["userpwdConfirm"]
});
//其他的与上例类似,区别在于用updateOne
User.updateOne({username: userinfo.username}, {$set:{
userpwd:userinfo.userpwd,
userpwdConfirm:userinfo.userpwdConfirm
}},function (err, data) {
if (data.ok) {
res.json({
message:"修改密码成功"
})
} else {
res.json({
message:"修改密码失败"
})
}
});
});
查询登录(查)
router.get("/login",function(req,res,next){
//从mongodb中获取数据,并返回给客户端,用的是find
User.find({},function(err,result){
if(err){
res.json({issuccess:false,message:"mongon查询出错"});
}else{
res.json({
message:"查询成功",
data:result
})
console.log(result);
}
})
});