创建服务器 express ,mongodb实现表格增删改查

2022-07-25,,,,

Long Time No See

废话不多说,直接开整
前提是 Vscode 软件
1、首先,建立一个文件夹

2、然后,在文件夹里创建一个 public 文件夹,此文件夹用来放置静态文件

3、在静态文件夹里创建静态资源

4、静态资源创建完毕后,右键创建的第一个文件夹,在集成终端中打开

ps:集成终端为 node.js

5、在打开的集成终端中,输入 npm init -y +回车 创建 json 文件

6、再输入 npm install express mongoose -S 安装 expressmongoose

7、安装完成之后,在刚开始创立的文件夹下创建一个 服务器 ,一般命名为qpi.js,然后就可以开始敲代码了

服务器代码
JavaScript连接服务器代码
html代码
Css代码

顺序

一、首先写出接口文档,比如这个
一、静态资源发布 。http://127.0.0.1:4399 返回 index.html

二、接口文档
    1、添加商品
        接口地址:/addgoods
        请求方式:POST
        上传数据:imgsrc 图片地址、msg 简介、price 价格、 type 类别(1,2,3)
        返回响应:
                成功:{"err_code":"添加成功"}
                失败:{"err_code":"no"}

    2、返回所有商品
        接口地址:/allgoods
        请求方式:GET
        上传数据:
        返回响应:
                成功:{"err_code":"显示成功","info":[]}
                失败:{"err_code":"no"}
    3、删除商品
        接口地址:/delone
        请求方式:GET
        上传数据:id 商品唯一id
        返回响应:
                成功:{"err_code":"删除成功"}
                失败:{"err_code":"no"} 
    4、修改-通过id 查询 修改的商品数据
        接口地址:/findone
        请求方式:GET
        上传数据:id 商品唯一id
        返回响应:
                成功:{"err_code":"查找成功","info":{}}
                失败:{"err_code":"no"}

    5、修改
        接口地址:/editgoods
        请求方式:POST
        上传数据: id:  imgsrc 图片地址、msg 简介、price 价格、 type 类别(1,2,3)
        返回响应:
                成功:{"err_code":"修改成功"}
                失败:{"err_code":"no"}
二、创建服务器,并写出接口

服务器代码

三、链接服务器

JavaScript链接服务器


回到顶部

html代码

<div class="div">
        <h1>商品后台管理系统</h1>
        <form>
            <label for="imgsrc">图片地址</label>
            <input type="text" id="imgsrc">

            <label for="msg">简介</label>
            <input type="text" id="msg">

            <label for="price">价格</label>
            <input type="text" id="price">

            <select name="" id="type">
                <option value="1">电脑</option>
                <option value="2">冰箱</option>
                <option value="3">手机</option>
            </select>

            <input type="button" value="添加" id="add" name=""/>
            <!-- 添加一个输入框,用于确认修改时的id值,可默认隐藏 -->
            <input type="text" name="" id="_id"/>
            <input type="button" name="" id="edit" value="确认修改"/>
        </form>

        <table>
            <thead>
                <tr>
                    <th>图片</th>
                    <th>简介</th>
                    <th>价格</th>
                    <th>类别</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="tbody">
                <!-- <tr>
                    <th></th>
                    <th></th>
                    <th></th>
                    <th></th>
                    <th>
                        <span>修改</span>
                        <span>删除</span>
                    </th>
                </tr> -->
            </tbody>
        </table>
    </div>

回到顶部

Css样式代码

		.div{
            width: 100vw;
        }
        h1{
            text-align: center;
        }
        table,th,td{
            border: 1px solid blue;
            border-collapse: collapse;
        }
        table{
            table-layout: auto;
        }
        #tbody span{
            cursor: pointer;
        }

        table{
            width: 80vw;
        }
        table img{
            width: 50px;
            height: 50px;
        }
        #_id,#edit{
            display: none;
        }

回到顶部

JavaScript代码

//添加
        var add=document.getElementById( "add" );
            add.onclick=function(){
                var imgsrc=document.getElementById( "imgsrc" ).value;
                var msg=document.getElementById( "msg" ).value;
                var price=document.getElementById( "price" ).value;
                var type=document.getElementById( "type" ).value;


                var xhr=new XMLHttpRequest();
                    xhr.open( "POST","/addgoods",true );
                    xhr.setRequestHeader( "Content-type","application/x-www-form-urlencoded" )
                    xhr.send( `imgsrc=${ imgsrc }&msg=${ msg }&price=${ price }&type=${ type }` )
                    xhr.onreadystatechange=function(){
                        if( xhr.readyState==4 && xhr.status==200 ){
                            xhr.responseText;
                            let obj=JSON.parse( xhr.responseText );

                            if( obj.err_code=="添加成功" ){
                                //==展示表格,稍后再议
                                shows()
                            }else{
                                alert( "添加失败" )
                            }
                        }
                    }
            }

            var Arr=[ "电脑","冰箱","手机" ]
            //渲染2--1
            function showTr( obj ){
                var tr="";
                    for( let i in obj.info ){
                        tr+=`
                        <tr>
                            <th>
                                <img src="${ obj.info[i].imgsrc }" alt=""/>    
                            </th>
                            <th>${ obj.info[i].msg }</th>
                            <th>${ obj.info[i].price }</th>
                            <th>${ Arr[ obj.info[i].type-1 ] }</th>
                            <th>
                            <span οnclick="change( '${ obj.info[i]._id }' )">修改</span>
                            <span οnclick="del( '${ obj.info[i]._id }' )">删除</span>
                            </th>
                        </tr>

                                    `
                    }
                    document.getElementById( "tbody" ).innerHTML=tr
            }
            
            //显示再表格中2--2
            function shows(){
                var xhr=new XMLHttpRequest();
                    xhr.open( "GET","/allgoods",true )
                    xhr.send();
                    xhr.onreadystatechange=function(){
                        if( xhr.readyState==4 && xhr.status==200 ){
                            let obj=JSON.parse( xhr.responseText );

                            if( obj.err_code=="显示成功" ){
                                showTr( obj );
                            }else{
                                alert( "服务器没了" )
                            }
                        }
                    }
            }

            window.onload=function(){
                shows()
            }

            //3、删除商品
            function del( id ){
                var xhr=new XMLHttpRequest();
                    xhr.open( "GET",`/delone?id=${ id }`,true )
                    xhr.send();
                    xhr.onreadystatechange=function(){
                        if( xhr.readyState==4 && xhr.status==200 ){
                            let obj=JSON.parse( xhr.responseText )
                            if( obj.err_code=="删除成功" ){
                                shows()
                            }else{
                                alert( "删除失败" )
                            }
                        }
                    }
            }

            //4、修改
                //4-1、根据id查找
                function change( id ){
                    //点击修改时,确认修改显示,添加隐藏
                    document.getElementById( "edit" ).style.display="block";
                    document.getElementById( "add" ).style.display="none"

                    var xhr=new XMLHttpRequest();
                        xhr.open( "GET",`/findone?id=${ id }`,true )
                        xhr.send()
                        xhr.onreadystatechange=function(){
                            if( xhr.readyState==4 && xhr.status==200 ){
                                let obj=JSON.parse( xhr.responseText )
                                if( obj.err_code=="查找成功" ){
                                    //将值返回到表单中
                                    document.getElementById( "_id" ).value=obj.info._id
                                    document.getElementById( "imgsrc" ).value=obj.info.imgsrc;
                                    document.getElementById( "msg" ).value=obj.info.msg
                                    document.getElementById( "price" ).value=obj.info.price
                                    document.getElementById( "type" ).value=obj.info.type
                                }else{
                                    alert( "就这?" )
                                }
                            }
                        }
                }

                //4-2、确认修改
                var edit=document.getElementById( "edit" )
                    edit.onclick=function(){
                        //点击确认修改时,隐藏该按钮,添加按钮再显示
                        document.getElementById( "edit" ).style.display="none";
                        document.getElementById( "add" ).style.display="block"

                        //获取返回表单的值
                        var id=document.getElementById( "_id" ).value
                        var imgsrc=document.getElementById( "imgsrc" ).value
                        var msg=document.getElementById( "msg" ).value
                        var price=document.getElementById( "price" ).value
                        var type=document.getElementById( "type" ).value
                        var xhr=new XMLHttpRequest();
                            xhr.open( "POST","/editgoods",true )
                            xhr.setRequestHeader( "Content-type","application/x-www-form-urlencoded" )
                            xhr.send( `id=${ id }&imgsrc=${ imgsrc }&msg=${ msg }&price=${ price }&type=${ type }` )
                            xhr.onreadystatechange=function(){
                                if( xhr.readyState==4 && xhr.status==200 ){
                                    let obj=JSON.parse( xhr.responseText );

                                    if( obj.err_code=="修改成功" ){
                                        shows()
                                    }else{
                                        alert( "快改!" )
                                    }
                                }
                            }
                       
                        
                    }


回到顶部

## 服务器代码

//载入 rxpress 模块,创建服务器
const express=require("express");
const app=express();

//静态资源
app.use( express.static( "public" ) );

//加入 POST 必备两句话
app.use( express.json() );
app.use( express.urlencoded( { extended:true } ) );

//载入 mongoose 模块
    const mongoose=require("mongoose");
    //连接数据库
    mongoose.connect( "mongodb://127.0.0.1:27017/myJd",{ useUnifiedTopology: true,useNewUrlParser: true } )
    //创建 骨架
    let Schema=new mongoose.Schema( {
        "imgsrc":String,
        "msg":String,
        "price":Number,
        "type":String
    } )
    //生成 集合以及数据模型
    let datasModel=mongoose.model( "datas",Schema );


//添加商品
app.post( "/addgoods",function( req,res ){
    let imgsrc=req.body.imgsrc;
    let msg=req.body.msg;
    let price=req.body.price;
    let type=req.body.type;

    datasModel.create( { 
        "imgsrc":imgsrc,
        "msg":msg,
        "price":price,
        "type":type 
    },function( err ){
        if( err ){
            res.send( { "err_code":"添加失败" } )
        }else{
            res.send( { "err_code":"添加成功" } )
        }
    } )
} )


//显示所有商品
app.get( "/allgoods",function( req,res ){
    datasModel.find( {},function( err,data ){
        if( err ){
            res.send( { "err_code":"溜了溜了" } )
        }else{
            res.send( { "err_code":"显示成功","info":data } )
        }
    } )
} )


//删除商品
app.get( "/delone",function( req,res ){
    let id=req.query.id
    datasModel.deleteOne( { "_id":id },function( err ){
        if( err ){
            res.send( { "err_code":"爷错了,快改" } )
        }else{
            res.send( { "err_code":"删除成功" } )
        }
    } )
} )


//修改
    //1、通过id 查询需要修改的数据
    app.get( "/findone",function( req,res ){
        const id=req.query.id;
        datasModel.findOne( { "_id":id },function( err,data ){
            if( err ){
                res.send( { "err_code":"爷又错了!快改!" } )
            }else{
                res.send( { "err_code":"查找成功","info":data } )
            }
        } )
    } )

    //2、修改==
    app.post( "/editgoods",function( req,res ){
        let id=req.body.id;
        let imgsrc=req.body.imgsrc;
        let msg=req.body.msg;
        let price=req.body.price;
        let type=req.body.type;

        datasModel.updateOne( { "_id":id },{ $set:{ 
            "imgsrc":imgsrc,
            "msg":msg,
            "price":price,
            "type":type 
         } },function( err ){
            if( err ){
                res.send( { "err_code":"哎!又错了!" } )
            }else{
                res.send( { "err_code":"修改成功" } )
            }
        } )
    } )


app.listen( 4399 )

回到顶部

🆗,搞定,今天的分享也结束了
我后天会稍微介绍一下 node 和 express
大家拜拜~~

本文地址:https://blog.csdn.net/Qi_JC/article/details/111936766

《创建服务器 express ,mongodb实现表格增删改查.doc》

下载本文的Word格式文档,以方便收藏与打印。