在 Vue3 中,可以使用 Axios 库来发送 HTTP 请求向后端请求数据,并将数据返回给前端页面。

首先,你需要在前端项目中安装 Axios 库:

npm install axios

然后,在你的 Vue 组件中,可以使用 Axios 发送 GET 请求获取后端数据的示例代码如下:

import axios from 'axios';

export default {
  data() {
    return {
      backendData: [] // 存储从后端返回的数据
    };
  },
  mounted() {
    this.getDataFromBackend();
  },
  methods: {
    getDataFromBackend() {
      axios.get('/api/data') // 发送 GET 请求到后端的 '/api/data' 路径
        .then(response => {
          this.backendData = response.data; // 将后端返回的数据保存到前端组件的数据中
        })
        .catch(error => {
          console.error(error);
        });
    }
  }
};

在后端,你可以使用任何后端框架(如 Express、Koa、Laravel 等)来处理请求并从 MySQL 数据库中获取数据。以下是一个使用 Express 框架的示例:

const express = require('express');
const mysql = require('mysql');

const app = express();
const port = 3000;

// 创建数据库连接
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'your_username',
  password: 'your_password',
  database: 'your_database'
});

// 连接数据库
connection.connect();

// 处理前端发送的 GET 请求
app.get('/api/data', (req, res) => {
  // 在这里执行数据库查询操作
  connection.query('SELECT * FROM your_table', (error, results) => {
    if (error) {
      console.error(error);
      res.status(500).send('Internal Server Error');
    } else {
      res.send(results); // 将数据库查询结果作为响应发送给前端
    }
  });
});

// 启动服务器
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

注意,上述示例代码仅为演示目的,并未处理数据库连接的安全性、错误处理等方面的问题。在实际项目中,你需要根据具体需求进行适当的安全和错误处理。

Vue3 前后端数据交互:使用 Axios 获取 MySQL 数据

原文地址: http://www.cveoy.top/t/topic/qpli 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录