用node+mysql创建简单的接口

117 阅读1分钟

node 与 数据库连接

1.实现准备
  • express 包:npm i express Or yarn add express
2.实现步骤
http.ts 文件
  • 引入 express 包

const express = require('express')

  • 创建 app 对象

const app = express()

  • 设置跨域,解决问题
 app.all('*',(req:any,res:any,next:any) => {
 //设置允许跨域的域名,*代表允许任意域名跨域
  res.header("Access-Control-Allow-Origin", req.headers.origin || '*');
  // //只允许http://xxx.xx.xx/可跨
  //res.header('Access-Control-Allow-Origin', 'http://xxx.xx.xx/');
  //允许的header类型
  res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
  //跨域允许的请求方式 
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  // 可以带cookies
  res.header("Access-Control-Allow-Credentials", true);
  if (req.method == 'OPTIONS') {
    res.sendStatus(200);
  } else {
    next();
  }
})
  • 路由格式,响应的接口 (hotWord.getHostWord) 在另一个文件写处理函数

    app.get('/', hotWord.getHostWord)

  • 监听端口
  app.listen(3000, () => {console.log('服务启动: http://localhost:3000')})```
hot-weord.ts 文件 连接数据库 处理数据
  • 1.导入 mysql 模块

const mysql = require('mysql')

  • 2.创建数据库连接,配置基本属性
const connection = mysql.createConnection({ 
  host: 'xxxxx', // 数据库地址
  user: 'xxxx', // 数据库账号
  password: 'xxxx', // 数据库密码
  database: 'xxxx' // 数据库名称
})```
  • 3.请求处理
  const getHostWord = (req: any, res: any) => {
    let sql = 'select * from hot_word'
    connection.query(sql, (err: any, data: any) => {
        if(err) return console.log('SELECT ERROR-',err);
        res.send(JSON.parse(JSON.stringify(data)))
        console.log('----------------数据请求成功-------------------');
        console.log(JSON.parse(JSON.stringify(data)));
  })
}```
  • 4.抛出方法
  module.exports = {
    getHostWord
}
在前端页面调用
// 引入 axios 
import axios from 'axios'// 获取热词表数据
export function getHotWord() {
  axios.get('http://localhost:3000')
    .then(res => {
      console.log(res.data);
    })
    .catch(err => {
      console.log(err);
    })
}