微涉全栈(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
相关推荐
rising start4 分钟前
前端基础一、HTML5
前端·html·html5
鬼谷中妖13 分钟前
JavaScript 循环与对象:深入理解 for、for...in、for...of、不可枚举属性与可迭代对象
前端
大厂码农老A18 分钟前
你打的日志,正在拖垮你的系统:从P4小白到P7专家都是怎么打日志的?
java·前端·后端
im_AMBER20 分钟前
CSS 01【基础语法学习】
前端·css·笔记·学习
DokiDoki之父23 分钟前
前端速通—CSS篇
前端·css
pixle027 分钟前
Web大屏适配终极方案:vw/vh + flex + clamp() 完美组合
前端·大屏适配·vw/vh·clamp·终极方案·web大屏
ssf198733 分钟前
前后端分离项目前端页面开发远程调试代理解决跨域问题方法
前端
@PHARAOH33 分钟前
WHAT - 前端性能指标(加载性能指标)
前端
尘世中一位迷途小书童38 分钟前
🎨 SCSS 高级用法完全指南:从入门到精通
前端·css·开源
非凡ghost43 分钟前
火狐浏览器(Firefox)tete009 Firefox 多语便携版
前端·firefox