纯小白从前端跨域发起axios get请求获取数据
如果有兴趣欢迎往下看:
//nodejs部分
const express = require('express')
const app = express()
const mysql = require('mysql2')
// 创建一个数据库连接
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'users',
password: '203827'
});
connection.connect((err) => {
if (err) {
console.error('Error connecting to the database:', err.message);
return;
}
console.log('Connected to the MySQL database.');
});
app.get('/user', (req, res) => {
const query = 'SELECT * FROM inf';
connection.query(query, (err, results) => {
if (err) {
console.error('Error fetching posts:', err);
return res.status(500).json({ message: 'Error fetching posts' });
}
res.json(results);
});
// res.send('test')
})
app.listen('8000', () => {
console.log('8000启动')
})
//关闭数据库
// connection.end((err) => {
// if (err) {
// console.error('Error closing the connection:', err.message);
// return;
// }
// console.log('Database connection closed.');
// });
//前端部分
import './App.css'
import axios from 'axios'
function App() {
const test=()=>{
axios({
method:'get',
url:'api/user/'
}).then(res=>{
console.log(res)
})
}
return (
<>
<button onClick={test}>测试</button>
</>
)
}
export default App