这两天写一个小项目,不想用PHP写接口,太繁重。看了一圈后端云,发现都不咋运营了,进而打算自己写吧。然后看了nodejs,发现很轻量,而且还是js语言,这不是正好合我意,然后就开始研究起来。

	const express = require("express")

	const app = express()

	const mysql2 = require("mysql2")

	 
	app.get("/", async (req, res) => {

	    // 跨域

	    res.setHeader('Access-Control-Allow-Origin', '*');

	    res.setHeader("Access-Control-Allow-Headers", "X-Requested-With");

	    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");

	    // 创建连接池

	    const config = getDBConfig()

	    const promisePool = mysql2.createPool(config).promise()

	    let urls = req.query

	    var name = null;//用来记录第一个键值对的值

	    for (var key in urls) {

	        name = urls[key];

	        break;

	    }

	    console.log(name, "url参数");

	    let lit = await promisePool.query(`select * from one where name like "%${name}%"`)

	    console.log(lit, '结果');

	    res.send(lit);

	}).listen(3000)

	 
	function getDBConfig() {

	    return {

	        host: "127.0.0.1",

	        port: 3306,

	        user: "root",

	        password: "root",

	        database: "instructions",

	        connectionLimit: 1    //连接池

	    }

	}