因为直接在前端(浏览器中的React)连接数据库可能会带来安全风险。
在React应用中连接数据库,通常我们不会直接在React组件中连接数据库
而是通过后端服务器(如Node.js)来连接。
- 设置Node.js后端:
需要设置一个Node.js服务器。使用Express或其他框架。
以下是一个简单的Express应用示例,使用MySQL数据库:
const express = require('express');
const mysql = require('mysql');
const app = express();
// 创建数据库连接
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'mydb'
});
connection.connect((err) => {
if (err) throw err;
console.log('Connected to the MySQL server.');
});
// 定义一个简单的API端点
app.get('/data', (req, res) => {
connection.query('SELECT * FROM mytable', (err, result) => {
if (err) throw err;
res.send(result);
});
});
- 在React中调用API:
当Node.js服务器运行并开始监听端口时,可以在React应用中通过fetch或其他HTTP库(如Axios)来调用该API。
以下是一个简单的React组件示例,使用fetch
从Node.js服务器获取数据:
import React, { useEffect } from 'react';
function DataFetcher() {
useEffect(() => {
fetch('/data')
.then(response => response.json())
.then(data => console.log(data)) // 这里可以处理数据,并更新组件状态等。
.catch(error => console.error('Error:', error));
}, []); // 仅在组件挂载时执行。如果需要更频繁的获取数据,请修改此依赖数组。
return (null); // 只是获取数据。
}
export default DataFetcher;