nodejs结合mongodb操作数据库生成api接口ajax调用

静态接口
在前端人员和后端人员的协作中,肯定会遇到接口还没有开发完毕,但是前端人员又需要接口来调用数据展示的问题,如果抛开nodeJs不提,其实还是有办法的,那就是 Mock数据,俗称模拟数据,又称为假数据,对我们一般的数据调用其实是可以满足的:
https://www.easy-mock.com/login
那么利用node.js怎么样来做模拟数据呢

// var express = require('express');
// var app = express();
// var bodyParser = require('body-parser');
// app.use(bodyParser.json());
// app.use(bodyParser.urlencoded({ extended: true }));


// // 设置跨域
// app.all('*',function(req))


var express = require('express');
var app = express();
var bodyParser = require('body-parser');
//引用bodyParser 这个不要忘了写 
app.use(bodyParser.json());
// for parsing application/json 
app.use(bodyParser.urlencoded({ extended: true }));
// for parsing application/x-www-form-urlencoded //设置跨域访问
app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8"); next();
});
var questions = {
    "status":"0",
    "result":[
      {
          "id":"2",
          "productName":"概览",
          "url":"/index.php/index/countpage/index",
          "icon":"fa-home",
          "data":[],
          "openType":"1"

      },
      {
        "id":"3",
        "productName":"发布管理",
        "icon":"glyphicon-list",
        "openType":"0",
        "data":[
          { "id":"103","productName":"直播活动发布","url":"/index.php//index/index/activity"},
          { "id":"101","productName":"图文发布","url":"/content/index/add"},
          { "id":"104","productName":"视频发布","url":"/index.php//index/videopublish/video_add"}
        ]
      },
      {
        "id":"1",
        "productName":"商城管理",
        "url":"/index.php/index/shop/index",
        "icon":"fa-list-alt",
        "data":[],
        "openType":"1"
      },
      {
        "id":"4",
        "productName":"广播互动",
        "url":"null",
        "icon":"",
        "data":[],
        "openType":"1"
       },
     
      {
        "id":"4",
        "productName":"云导播台",
        "url":"/index.php/director/Index/index",
        "icon":"fa-cloud",
        "data":[],
        "openType":"1"
      },
     
      {
        "id":"5",
        "productName":"内容管理",
        "icon":"fa-th-large",
        "openType":"0",
        "data":[
          { "id":"123","productName":"直播活动管理","url":"/index.php/index/index/index"},
          { "id":"124","productName":"图文管理","url":"/index.php/index/resou/pic?column=-2"},
          { "id":"125","productName":"视频管理","url":"/index.php/index/videopublish/index"},
          { "id":"126","productName":"收录库","url":"/index.php/index/resou/look?column=-2"},
          { "id":"127","productName":"视频库","url":"/index.php/index/resou/video?column=-2"},
          { "id":"128","productName":"动态库","url":"/index.php/index/resou/dynamic"}
        ]
      },
      {
        "id":"6",
        "productName":"个性化管理",
        "icon":"fa-list-alt",
        "openType":"0",
        "data":[
          { "id":"123","productName":"基础信息设置","url":"/index.php/index/management/basic"},
          { "id":"124","productName":"默认封面图","url":"/index.php/index/management/background.html"},
          { "id":"125","productName":"手机号验证","url":"/index.php/index/management/phone"},
          { "id":"126","productName":"域名与公众号定制","url":"/index.php/index/management/domain.html"},
          { "id":"127","productName":"公众号验证","url":"/index.php/index/management/wechat.html"},
          { "id":"128","productName":"APP引流设置","url":"/index.php/index/management/app_drainage.html"}
        ]
      },
      {
        "id":"7",
        "productName":"财务管理",
        "icon":"fa-database",
        "openType":"0",
        "data":[
          { "id":"123","productName":"支出管理","url":"/index.php/index/finance/expenses"},
          { "id":"124","productName":"收入管理","url":"/index.php/index/finance/earning"}
        ]
      },
      {
        "id":"8",
        "productName":"工作群 ",
        "icon":"fa-users",
        "url":"/index.php/index/users/index",
        "data":[],
        "openType":"1"
      },
      {
        "id":"9",
        "productName":"统计数据 ",
        "icon":"glyphicon-stats",
        "url":"/index.php/index/countcontroller/index",
        "data":[],
        "openType":"1"
      },
      {
        "id":"11",
        "productName":"账户管理",
        "icon":"glyphicon-book",
        "openType":"0",
        "data":[
          { "id":"123","productName":"账户信息","url":"/index.php/index/account"},
          { "id":"124","productName":"认证信息","url":"/index.php/index/account/authentication"},
          { "id":"124","productName":"密码管理","url":"/index.php/index/account/password"}
        ]
      },
      {
        "id":"12",
        "productName":"开发者",
        "icon":"fa-wrench",
        "openType":"0",
        "data":[
          { "id":"123","productName":"开发者文档","url":"http://console.juyun.tv/wiki/?file=001-%E7%9B%B4%E6%92%AD/01-%E7%9B%B4%E6%92%AD%E5%88%97%E8%A1%A8"},
          { "id":"124","productName":"资源推送","url":"/push"}
        ]
      },
      {
        "id":"13",
        "productName":"推广服务",
        "icon":"fa-external-link",
        "url":"/index.php/index/promotion/index",
        "data":[],
        "openType":"1",
      }
   
    ] }
//写个接口123 
app.get('/list', function (req, res) {
    res.status(200),
        res.json(questions)
});

var quert =     [{ data: 203, name: '李慷', id: 12 },
                 { data: 456, name: '贺楠', id: 13 },
                 { data: 457, name: '小明', id: 14 },
                 { data: 458, name: '小米', id: 15 }];
//写个接口123 
app.get('/item', function (req, res) {
    res.status(200),
        res.json(quert)
});

app.post('/wdltest', function (req, res) {
    console.log(req.stack);
    console.log(req.body);
    console.log(req.url);
    console.log(req.query);
    res.json(req.body)
})
//配置服务端口 
var server = app.listen(81, function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log('Example app listening at http://%s:%s', host, port);
})

cnpm i (依赖包下载)
预览访问: http://121.36.8.98:81/list
截图:

image.png

客户端ajax调用:

    //get请求 
            $.ajax(
                {
                    type: 'get',
                    url: 'http://121.36.8.98:81/list',
                    success: function (data) {
                        console.log(data);
                    },
                    error: function (err) {
                        console.log(err)
                    }
                })

  1. npm install express

node操作数据库增删改查:
查询数据json返回:

var express = require('express');
var app = express();
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017";
 
 
app.get('/search', function (req, res) {   
  
    MongoClient.connect(url,{useNewUrlParser:true},function(err, db) {
        if (err) throw err;
        console.log("数据库已创建!");
         var dbase=db.db("shop");
         dbase.collection("users"). find().toArray(function(err, result) { 
            if (err) throw err;
            // 发送响应数据 
            res.send(JSON.stringify(result));
            db.close();
        });
});
})
 
var server = app.listen(8081, function () {
 
  var host = server.address().address
  var port = server.address().port
 
  console.log("应用实例,访问地址为 http://%s:%s", host, port)
})

image.png

增删改查操作node:


//创建网站服务器实现客户端和服务端交互:
const http = require('http')
//链接数据库:
const mongoose = require('mongoose')
//请求地址模块:
const url = require('url')
const querystring = require("querystring");
mongoose.connect('mongodb://localhost/shop', { useNewUrlParser: true })
    .then(() => console.log('成功'))
    .catch(() => console.log('失败'))
//创建用户集合规则:
const userSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true,
        // minlength: 2,
        // maxlength: 16
    },
    author: {
        type: String,
        // minlength: 18,
        // maxlength: 80
    },
    content: String,
    date: String,
    hobbies: [String]

})
//创建集合:  
const User = mongoose.model('User', userSchema)
//导入json :    mongoimport -d playground -c users --file ./users.json    

// User.create({
//     title: "李慷账户2",
//     author: '李慷',
//     password: "123456",
//     email: "[email protected]",
//     hobbies: "读书"
// }, (err, result) => {
//     console.log(err)
//     console.log(result)
// })






//创建服务器:
const app = http.createServer()
//为服务器添加请求事件:
app.on('request', async (req, res) => {

    //请求方式
    const method = req.method;
    //请求地址
    const { pathname, query } = url.parse(req.url, true);
    if (method == "GET") {
        //     //呈现用户页面
        if (pathname == '/list') {
            let users = await User.find()
            console.log(users)
            let list = `
            
            
                
                
                
                展示列表
            
            
            
                
            
            `;
            //数据循环展示;
            users.forEach(item => {
                list += `

标题:${item.title} 作者:${item.author} 作者:${item.content} 发布时间:${item.date}

` item.hobbies.forEach(item => { list += `${item}` }) list += ` ` }) res.end(list) } else if (pathname == '/add') { //添加用户表单界面 let add = ` 添加列表

文学作品 新闻时政 互联网技术

` res.end(add) } else if (pathname == '/modify') { //修改用户表单界面 //通过id获取参数修改 let user = await User.findOne({ _id: query.id }) console.log(user) let hobbies = ['文学作品', '新闻时政', '互联网技术'] let modify = ` 修改列表
`; hobbies.forEach(item => { //判断当前参数在不在返回值当中: let isbbies = user.hobbies.includes(item) if (isbbies) { modify += `${item} ` } else { modify += `${item} ` } }) modify += `
` res.end(modify) } else if (pathname == '/remove') { //删除功能逻辑: await User.findOneAndDelete({ _id: query.id }) res.writeHead(301, { Location: '/list' }); res.end(); } } else if (method == "POST") { //用户添加功能 if (pathname == '/add') { //接收用户参数: let formData = "" req.on('data', param => { formData += param }) req.on('end', async () => { console.log(formData) //将数据添加到数据库当中 let user = querystring.parse(formData) await User.create(user) //用户数据提交完毕重定向: res.writeHead(301, { Location: '/list' }); res.end(); }) } else if (pathname == '/modify') { //接收用户参数: let formData = "" req.on('data', param => { formData += param }) req.on('end', async () => { console.log(formData) //将数据添加到数据库当中 let user = querystring.parse(formData) await User.updateOne({ _id: query.id }, user) //用户数据提交完毕重定向: res.writeHead(301, { Location: '/list' }); res.end(); }) } } }) //监听端口: app.listen(3001)

你可能感兴趣的:(nodejs结合mongodb操作数据库生成api接口ajax调用)