node.js link database

node.js link database

1. Premise

  1. The computer has installed node, you can use the win+R key, enter cmd, and then enter, node -v, check the version;
    .insert image description here

  2. Then enter npm -V to check the installed version of npm
    insert image description here

  3. After all the above, create an empty folder, name: projects, and create three empty folders in it, namely: jq, html, api
    insert image description here

  4. In the jq folder, introduce your own jq library
    insert image description here

2. Create a new JSON file

  • With vsCode, open the folder projects,
  • insert image description here
  • Select the api folder with the mouse, right-click, select to open in the integrated terminal, and enter: npm init (all the options inside, press Enter until the file path appears) Check whether package.json has appeared in the api folder documentinsert image description hereinsert image description here
    insert image description here
  • Then enter: npm install express mysql cor body-parser and wait for the installation. Two json files appear after installationinsert image description here
  • In the api folder, create two js files, namely http.js, db.js
  • insert image description here

3. Write code

  • First open the http.js file and import the library we have installed
//引入模块
const express=require('express');
const app=express();
const url=require('url')
const db=require('./db.js');
  • Solving Cross-Region Issues
// 解决跨区域问题
// 导入中间件 cors
const cors = require('cors');
// 在路由之前调用app.use(cors())配置中间件
app.use(cors());
app.all("*",function(req,res,next){
    
    
 res.header("Acess-Control-Allow-Origin","*");
 next();
})
  • Set the port; open the terminal in the api folder and enter node http.js to test whether the setting is successful
// 设置端口
app.listen(8888,function(){
    
    
  console.log('正在启动888....');
})

insert image description here

  • We open the db.js file and connect to the database (note that the name of the database is the same as that of the database we called, and the user name and password are also the same as those of our own database)
// 引入mysql中间件
const mysql=require('mysql')
// 创建连接
let connection=mysql.createConnection({
    
    
  // host 数据库主机名
  host:"localhost",
  // user 用户名
  user:"root",
  // password 密码
  password:"123456",
  // 所连接的数据库名称
  database:"in37"
})
//连接数据库
connection.connect();

insert image description hereinsert image description here

  • Because I already have a table in the database here, the next data is mainly written around this table.insert image description here
  • Next throw the student number and name
// 前面一个参数为获取路径,这个路径可以自己取,为了方便,这里写的是/表名/getOne  ,后面的req:request 请求,res:response 响应;callback 返回值
module.exports.selectBySno=function(sno,sname,callback){
    
    
  let sql=`select * from student where sno='${sno}' and sname='${sname}'`;
  connection.query(sql,function(err,data){
    
    
    callback(data);
  })
}
  • Return to the method of writing and obtaining data in the http.js file,
//通过学号和姓名登录 get请求得到数据
// let 两个变量分别请求url,获取到学号和姓名,并且采用三元写法,若返回值为undefined,则为空,否则返回对应的值
app.get('/student/getOne',(req,res)=>{
    
    
  let sno=url.parse(req.url,true).query.sno==undefined?"":url.parse(req.url,true).query.sno;
  let sname=url.parse(req.url,true).query.sname==undefined?"":url.parse(req.url,true).query.sname;
  connection.query(sql,function(err,data){
    
    
    callback(data);
  })
})

  • We need to create an HTML page to test whether the call to the database is successful. Create a login.html page and an index.html page for jumping. The login condition here is the input student number and name, which must match the called database. The data in the tables in the
<body>
  <table>
    <tr>
      <td>学号</td>
      <td><input type="text" id="tSno"></td>
    </tr>
    <tr>
      <td>姓名</td>
      <td><input type="text" id="tSname"></td>
    </tr>
    <tr>
      <td colspan="2"></td>
      <button id="btnLogin">登录</button>
    </tr>
  </table>
</body>

insert image description here

  • Introduce our jq library after the body tag, and use jq to write the call request in the page
<script src="../jq/jquery-3.5.1.min.js"></script>
<script>

  $(function(){
    
    
    // 给登录按钮设置点击事件
   $("#btnLogin").click(function(){
    
    
    $.ajax({
    
    
      url:"http://127.0.0.1:8888/student/getOne",
      data:{
    
    
        sno:$("#tSno").val(),
        sname:$("#tSname").val(),
      },
      // 
      success:function(result){
    
    
        if(result.data.length>0){
    
    
          alert("登录成功");
          window.location.href="./index.html";
        }else{
    
    
          alert("登录失败");
          $("#Sno").val("");
          $("#Sname").val("");
        }
      }
    })
   })
  })
</script>
  • Realize the effect
    insert image description here
    insert image description here
    At this point, you will successfully connect to the database content and successfully log in to jump

Guess you like

Origin blog.csdn.net/weixin_44042442/article/details/123358945