Use nodeJS to create an API interface and connect to the mysql database

1. Preliminary preparation

It doesn't matter if you don't understand, just imitate the code directly, the things you need to download vscode, nodeJS, mysql

2. Main operation

Create a js file index.js

Open and install express and mysql dependencies in vscode


```bash
npm i express -S
npm i mysql -S


Copy directly into the file

const express = require('express');
const app = express();
const mysql = require('mysql');

const connection = mysql.createConnection({
    
    
    host: 'localhost',
    user: 'root',
    password: '123456',     // 改成你自己的密码
    database: 'test'    // 改成你的数据库名称
});

connection.connect();

// 下面是解决跨域请求问题
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();
 });

// 这里就是主要要修改的地方,其实也就一行
// 把 address 改成你自己定的地址,就是连接访问的那个地址
app.get('/address',function(err,res){
    
    
    const sql = 'select * from carousel'; // 写你需要的sql代码,你要是不会写那我就真的没办法了
    connection.query(sql,function(err,result){
    
    
        if(err){
    
    
            console.log('[SELECT ERROR] - ', err.message);
            return;
        }
        // result内放的就是返回的数据,res是api传数据
        // 返回的数据需要转换成JSON格式
        res.json(result); 
    }); 
})    

var server = app.listen(8081, '127.0.0.1', function () {
    
    

    var host = server.address().address;
    var port = server.address().port;

    console.log("地址为 http://%s:%s", host, port);
})

Finally execute node server.js (file name)

Enter 127.0.0.1::8081/address in the browser, and change the address to what you set

Only get is demonstrated here, and post cannot be used directly. You need to introduce a third-party plug-in
app.get() can be more than one, copy and paste, change the address and change it to the SQL statement of the function you want to execute. The
ip address and port can be used by yourself Change, if you want to put it on your own server, change the ip to the internal network address of the server.
Mysql will automatically disconnect for a long time (8 hours). This situation is basically not encountered locally, so you need to add more when you put it on the server. A callback, specifically refer to this boss server closed

Guess you like

Origin blog.csdn.net/weixin_44982333/article/details/103290994