微涉全栈(react,axios,node,mysql)

纯小白从前端跨域发起axios get请求获取数据

如果有兴趣欢迎往下看:

//nodejs部分

javascript 复制代码
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.');
// });

//前端部分

javascript 复制代码
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
相关推荐
三十岁老牛再出发2 小时前
07.27&7.28每日总结
c语言·mysql
东方小月3 小时前
从零开发一个 Coding Agent(四):使用状态机校验大模型事件流
前端·人工智能·后端
Csvn4 小时前
🧩 ESM vs CJS 混用的 7 个「天坑」——从 TypeScript 编译到 Node 与浏览器
前端
Csvn4 小时前
🎯 Web 性能 API 集合:Performance Observer 的 5 个冷门妙用
前端
Csvn4 小时前
深入 React 闭包陷阱:从根源上理解并根治 stale closure
前端
whyfail4 小时前
前端学 Spring Boot(8):接口为什么越用越慢?
前端·spring boot·后端
用户059540174465 小时前
LangChain 记忆测试踩坑实录:这两个坑让我排查了 4 小时
前端·css
程序员黑豆5 小时前
鸿蒙应用开发:@Monitor 装饰器使用教程
前端·harmonyos
SamChan905 小时前
在Web应用中集成PDF多语言翻译功能:PDFTranslator API实战指南
前端·python·ai·pdf·yapi·机器翻译
kyriewen6 小时前
AI Agent 9秒删光了生产数据库——我给自己的项目做了5个紧急检查
前端·ai编程·claude