express和mysql,开发接口
时间: 2023-05-27 07:01:58 浏览: 58
使用Express和MySQL开发接口的步骤如下:
1. 安装Express和MySQL模块
首先需要在项目中安装Express和MySQL模块。可以使用npm install命令进行安装:
npm install express mysql
2. 连接到MySQL数据库
使用MySQL模块中的createConnection方法连接到MySQL数据库:
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'database_name'
});
3. 编写接口
使用Express定义API接口,例如:
const express = require('express');
const app = express();
app.get('/users', (req, res) => {
connection.query('SELECT * FROM users', (error, results, fields) => {
if (error) throw error;
res.send(results);
});
});
其中,/users是API的路径,查询数据库中的users表数据,并将查询结果返回给客户端。
4. 启动服务器
调用app.listen启动服务器,例如:
app.listen(3000, () => {
console.log('Server started on port 3000');
});
完整的代码示例:
const express = require('express');
const mysql = require('mysql');
const app = express();
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'database_name'
});
app.get('/users', (req, res) => {
connection.query('SELECT * FROM users', (error, results, fields) => {
if (error) throw error;
res.send(results);
});
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});