暑假实践web前后端开发-笔记

(主要是前端开发,不做后端,前面先介绍一个实现了前后端的项目)

一. 安装和运行项目MoreMall

1.介绍项目MoreMall

已经实现前后端可以前后端交互,前端:client,后端:server;mall.sql中可以编写数据库。

2.环境搭建


1)安装Node.js:Node.js是一个JavaScript运行环境,用于构建服务器端应用程序。在官网[Node.js](https://nodejs.org/)下载并安装合适版本的Node.js。node.js的环境配置比较复杂。

2)安装mysql
3)安装依赖:在项目的根目录下运行`npm install`,这会根据`package.json`文件安装项目所需的所有依赖。

(MySQL):https://blog.csdn.net/chuci0910/article/details/138770174
(NodeJs):https://zhuanlan.zhihu.com/p/686043568

二. 创建Vue项目

1.使用Vue CLI创建项目

1)安装和创建vue项目:新建文件夹放项目文件——该文件目录下cmd——`vue create my-project`
2)项目目录结构:`src`目录下包含`components`、`views`等子目录,用于存放组件和页面。

3)在<template>脚本中编写数据
- **定义数据**:在Vue组件的`<script>`部分定义数据,通过`data`函数返回数据对象。
- **展示数据**:在Vue组件的`<template>`部分使用插值表达式`{{ }}`或指令`v-bind`等展示数据。

示例:component—foo.vue

<template>
	<div>{{msg}}</div>
</template>

<script>
export default{
	name:'foo',
	data(){
		return{
			msg:'foo page'
		}
	}
}
</script>

<style>
</style>

三. 安装和使用vue-router

这里以项目routetest展示

1.安装vue-router


1)安装:在你想要加上这个东西的项目文件目录下面cmd——`npm install vue-router`
2)配置路由:在`src/router/index.js`中配置路由规则,将不同的路径映射到不同的组件。

示例:

src/router/index.js文件中代码:

import { createRouter, createWebHistory } from 'vue-router';
import Home from '../components/Home.vue'; // 示例组件路径,请根据实际情况调整
import Bar from '../components/Bar.vue'; // 示例组件路径,请根据实际情况调整
import Foo from '../components/Foo.vue'; // 示例组件路径,请根据实际情况调整

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/bar',
    name: 'Bar',
    component: Bar
  },
  {
    path: '/foo',
    name: 'Foo',
    component: Foo
  }
  // 其他路由配置
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
});

export default router;

3)使用<router-link>和<router-view>
<router-link>:用于创建导航链接,点击后可以切换到相应的路由页面。
<router-view>:用于展示匹配到的路由组件。

示例:App.vue中:

<template>
  <div id="app">
      <router-link to="/bar">Bar</router-link>|
      <router-link to="/foo">Foo</router-link>  
    <router-view></router-view> <!-- 确保包含这个标签 -->
  </div>
</template>

页面展示:(注意看那个端口号)

点击bar:那为啥我这里端口号叫'/bar'

因为你记得router配置那里吗,就是path,这里name是可以随便取的,但是一般与component名字保持一致,而component名字是不能变的,对应的就是component-xx.vue。

为啥点击可以跳转——因为那个<router-link>,而<router-view>具体在页面上什么作用,后面说。

四.搭建第一个element-plus小程序

1.用上面的router+element-plus搭

element-plus可以理解为一个被做好了的打包了的一系列用于前端页面渲染的包(万能包可以这么理解,程序员不是程序员,我们只是包的搬运工)

2.怎么用他们的组件代码

点进官网Overview 组件总览 | Element Plus (element-plus.org)

 

3.安装element-plus


1)安装:在你要作用的项目文件中cmd—`npm install element-plus`。
2)引入element-plus:在`main.js`中引入Element Plus和样式文件

import ElementPlus from 'element-plus'//引入elementplus
import 'element-plus/dist/index.css'//引入elementplus样式文件


3)使用组件:在Vue组件中使用Element Plus的UI组件,如`<el-button>`、`<el-input>`等。

示例:App.vue中,反正以<el->开头的就是

<template>
  <el-container class="layout-container-demo" style="height: 500px">
      <el-aside width="200px">
        <el-scrollbar>
          <el-menu :default-openeds="['1', '3']">
            <el-sub-menu index="1">
              <template #title>
                <el-icon><Message /></el-icon>Navigator One
              </template>
              <el-menu-item-group>
                <template #title>Group 1</template>
                <el-menu-item index="1-1">
					<router-link to="/optionOne">Option 1</router-link>
				</el-menu-item>
                <el-menu-item index="1-2">
					<router-link to="/optionTwo">Option 2</router-link>
				</el-menu-item>
              </el-menu-item-group>
              <el-menu-item-group title="Group 2">
                <el-menu-item index="1-3">
					<router-link to="/optionThree">Option 3</router-link>
				</el-menu-item>
              </el-menu-item-group>
              <el-sub-menu index="1-4">
                <template #title>Option4</template>
                <el-menu-item index="1-4-1">Option 4-1
					<router-link to="/optionFour">Option4</router-link>
				</el-menu-item>
              </el-sub-menu>
            </el-sub-menu>
            <el-sub-menu index="2">
              <template #title>
                <el-icon><icon-menu /></el-icon>Navigator Two
              </template>
              <el-menu-item-group>
                <template #title>Group 1</template>
                <el-menu-item index="2-1">Option 1</el-menu-item>
                <el-menu-item index="2-2">Option 2</el-menu-item>
              </el-menu-item-group>
              <el-menu-item-group title="Group 2">
                <el-menu-item index="2-3">Option 3</el-menu-item>
              </el-menu-item-group>
              <el-sub-menu index="2-4">
                <template #title>Option 4</template>
                <el-menu-item index="2-4-1">Option 4-1</el-menu-item>
              </el-sub-menu>
            </el-sub-menu>
            <el-sub-menu index="3">
              <template #title>
                <el-icon><setting /></el-icon>Navigator Three
              </template>
              <el-menu-item-group>
                <template #title>Group 1</template>
                <el-menu-item index="3-1">Option 1</el-menu-item>
                <el-menu-item index="3-2">Option 2</el-menu-item>
              </el-menu-item-group>
              <el-menu-item-group title="Group 2">
                <el-menu-item index="3-3">Option 3</el-menu-item>
              </el-menu-item-group>
              <el-sub-menu index="3-4">
                <template #title>Option 4</template>
                <el-menu-item index="3-4-1">Option 4-1</el-menu-item>
              </el-sub-menu>
            </el-sub-menu>
          </el-menu>
        </el-scrollbar>
      </el-aside>
  
      <el-container>
        <el-header style="text-align: right; font-size: 12px">
          <div class="toolbar">
            <el-dropdown>
              <el-icon style="margin-right: 8px; margin-top: 1px">
                <setting />
              </el-icon>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>View</el-dropdown-item>
                  <el-dropdown-item>Add</el-dropdown-item>
                  <el-dropdown-item>Delete</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <span>Tom</span>
          </div>
        </el-header>
  
        <el-main>
          <el-scrollbar>
            <router-view></router-view>
          </el-scrollbar>
        </el-main>
		
      </el-container>
    </el-container>
</template>

4)这里说明<router-view>作用:

你看看我调整其位置之后,上图的'3'到哪去了。理解为占位符。

        <el-main>
          <el-scrollbar>
            
          </el-scrollbar>
        </el-main>
		
      </el-container>
    </el-container>
	<router-view></router-view>
</template>

4.这里同样实现了页面跳转,how


1)路由配置:在`src/router/index.js`中配置路由,每个路由对应一个组件。

示例:对了,如果path是'/',则代表第一个进来的页面就是这个。

好像没说怎么运行项目:项目文件目录下cmd—npm run serve

import{createRouter,createWebHistory} from 'vue-router';//导入外部组件,声明vue路由
import HelloWorld from '../components/HelloWorld.vue';
import OptionOne from '../components/OptionOne.vue';
import OptionTwo from '../components/OptionTwo.vue';
import OptionThree from '../components/OptionThree.vue';
import OptionFour from '../components/OptionFour.vue';

const routes=[//路由器配置
	{
		path:'/',//这样的话就最先进入的是helloworld页面了
		name:'HelloWorld',
		component:HelloWorld
	},
	{
		path:'/optionOne',
		name:'OptionOne',
		component:OptionOne
	},
	{
		path:'/optionTwo',
		name:'OptionTwo',
		component:OptionTwo
	},
	{
		path:'/optionThree',
		name:'OptionThree',
		component:OptionThree
	},
	{
		path:'/optionFour',
		name:'OptionFour',
		component:OptionFour
	}
];

const router=createRouter({
	history: createWebHistory(process.env.Base_URL),
	routes
});

export default router;


2)导航链接:使用`<router-link>`创建导航链接,点击后可以跳转到对应的页面,使用`<router-view>`展示路由组件。

<el-menu-item index="1-3">
      <router-link to="/optionThree">Option 3</router-link>  
</el-menu-item>

五. Vue-router、element-plus和axios结合使用

1.安装axios

1)同上,安装命令:`npm install axios`
2)配置axios:在`main.js`中配置axios实例,设置默认的baseURL和其他全局配置。

2.实现前后端的小程序


- **定义接口**:在服务端定义API接口,处理前端的请求,返回数据。
- **前端请求数据**:在前端组件中使用axios发送请求,获取数据并展示在页面上。
- **动态数据切换**:结合Element Plus的组件和Vue Router,实现菜单的动态数据切换,例如根据不同的菜单项展示不同的内容。

 具体步骤:
1)创建axios实例并配置:

import axios from 'axios';  
// 创建一个 axios 实例  
const http = axios.create({  
  baseURL: 'http://localhost:3000/',  
  // 其他配置...  
});  
  
// 创建一个 Vue 应用  
const app = createApp(App);  
  
// 将 axios 实例添加到 Vue 应用的原型上  
app.config.globalProperties.$http = http;  
  
// 挂载 Vue 应用  
app.mount('#app');

2)在Vue组件中使用axios发送请求request:
  

<script>
const tableData = [];
export default {
  name: 'HelloWorld',
  created() {
      this.getUserList();  
    }, 
    data() {  
        return {  
          // 假设我们从API获取的是一个用户列表  
          tableData
        };  
    }, 
    methods: {  
    getUserList() {
      this.$http.get('/').then(response => {  
            console.log(response.data)
            this.tableData = response.data; 
        })  
        .catch(error => {  
            console.log(error)  
        });  
    } 
    }
  
}
</script>

3)结合Element Plus和Vue Router实现动态菜单:前面已说明。

3.axios干啥的

Axios 是一个基于 Promise 的 HTTP 客户端,用于浏览器和 Node.js 环境中进行 HTTP 请求。它可以让你更方便地发送异步请求,并处理响应数据。在 Vue.js 项目中,你可以使用 Axios 来与后端 API 进行通信,例如获取数据、发送表单数据、处理文件上传等操作。axios 提供了简洁的 API,支持请求和响应的拦截器、请求取消、全局配置等功能,使得前后端的数据交互更加高效和可控。

1)首先在前面的项目基础上加一个src/server/index.js如下

const express = require('express');  
const app = express();  
const port = 3000; // 你可以选择任何未被占用的端口  
  
// 设置中间件以允许跨域请求(可选,根据你的需求)  
app.use((req, res, next) => {  
  res.header("Access-Control-Allow-Origin", "*");  
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");  
  next();  
});  
  
// 设置路由和响应  
app.get('/', (req, res) => {  
  // 创建一个对象,其中包含你想要返回的数据  
  const data = [  
  { id: 1, name: 'Alice', age:18, email: 'alice@example.com' },  
  { id: 2, name: 'Bob', age:19, email: 'bob@example.com' },  
  // ...更多用户  
  ];  
  
  // 使用res.json()方法发送JSON响应  
  res.json(data);  
});  
  
// 启动服务器  
app.listen(port, () => {  
  console.log(`Server is running on http://localhost:${port}`);  
});

这个代码的说明:

这个代码片段使用了 Node.js 和 Express 框架来创建一个简单的服务器。以下是对代码的逐行解释:

1. **导入 Express 模块并创建应用实例**:
   ```javascript
   const express = require('express');  
   const app = express();  
   ```

   - `express` 是一个用于构建 web 应用的框架。这里通过 `require('express')` 导入它,并通过 `express()` 创建一个应用实例。

2. **设置服务器监听的端口**:
   ```javascript
   const port = 3000; // 你可以选择任何未被占用的端口  
   ```

   - `port` 变量定义了服务器监听的端口号,这里设置为 `3000`。

3. **允许跨域请求的中间件设置**:
   ```javascript
   app.use((req, res, next) => {  
     res.header("Access-Control-Allow-Origin", "*");  
     res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");  
     next();  
   });  
   ```

   - 这段代码设置了一个中间件,以允许跨域请求(CORS)。它允许来自任何源的请求,并允许某些头部字段。`next()` 函数确保请求继续到下一个中间件或路由处理程序。

4. **定义路由和响应**:
   ```javascript
   app.get('/', (req, res) => {  
     // 创建一个对象,其中包含你想要返回的数据  
     const data = [  
       { id: 1, name: 'Alice', age:18, email: 'alice@example.com' },  
       { id: 2, name: 'Bob', age:19, email: 'bob@example.com' },  
       // ...更多用户  
     ];  
     
     // 使用 res.json() 方法发送 JSON 响应  
     res.json(data);  
   });  
   ```

   - `app.get('/', ...)` 定义了一个 GET 请求的路由,当客户端访问根路径 `/` 时,这个处理函数会被调用。
   - 处理函数创建了一个包含用户数据的对象 `data`,并使用 `res.json(data)` 将其作为 JSON 响应返回给客户端。

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

   - `app.listen(port, ...)` 启动服务器并让它监听定义的端口。
   - 当服务器启动成功时,会在控制台输出一条消息,表明服务器正在运行并且可以通过 `http://localhost:3000` 访问。

总结:这个代码片段创建了一个简单的 Express 服务器,可以响应对根路径 `/` 的 GET 请求,并返回一个包含用户数据的 JSON 响应。还设置了一个中间件来允许跨域请求。通过在 `3000` 端口运行这个服务器,你可以使用浏览器或其他 HTTP 客户端访问 `http://localhost:3000` 并查看返回的 JSON 数据。

2)运行

server文件目录下cmd—node index.js

可以看见后台数据

再在该项目文件目录下cmd—npm run serve,可以看到有数据啦!!

我如何管理后台数据?

就刚刚那个新加的server/index.js文件中:

// 设置路由和响应  
app.get('/', (req, res) => {  
  // 创建一个对象,其中包含你想要返回的数据  
  const data = [  
  { id: 1, name: 'Alice', age:18, email: 'alice@example.com' },  
  { id: 2, name: 'Bob', age:19, email: 'bob@example.com' },  
  // ...更多用户  
  ];  

六.五的基础上加上后端

如何把五的项目加上一中项目MoreMall的后端一起运行,就是前后端结合。

1.准备两个东西

1)mysql.sql

create database test;
use test;
CREATE TABLE user (  
    id INT AUTO_INCREMENT PRIMARY KEY,  
    name VARCHAR(255) NOT NULL, 
    password VARCHAR(255) NOT NULL,
    age VARCHAR(255) NOT NULL,
    email  VARCHAR(255) NOT NULL
);
INSERT INTO user (name, password,age,email) VALUES ('Bob', '123','23','123456@qq.com');
INSERT INTO user (name, password,age,email) VALUES ('Tom', '123','23','123456@qq.com');

2)server

放到scr文件下,但也可以并列,我之前的放过了,我也没删,反正在不同文件目录下npm run serve也是可以的

server下的两个文件:

(1)db.js

let mysql = require('mysql')
//配置链接数据库的参数
let db = mysql.createPool({
    host: '127.0.0.1',
    user: 'root',
	port:'3306',
    password: 'root',
    database: 'test'
})

module.exports = db

说明:

这段代码的目的是使用 Node.js 和 `mysql` 模块来创建一个连接到 MySQL 数据库的连接池,并将其导出以便在其他模块中使用。

具体解释如下:

1. **导入 `mysql` 模块**:
   ```javascript
   let mysql = require('mysql');
   ```
   这行代码导入了 `mysql` 模块,这是一个 Node.js 的库,用于连接和操作 MySQL 数据库。

2. **创建连接池**:
   ```javascript
   let db = mysql.createPool({
       host: '127.0.0.1',
       user: 'root',
       port: '3306',
       password: 'root',
       database: 'test'
   });
   ```
   这段代码使用 `mysql.createPool` 方法创建了一个连接池。连接池是一组数据库连接,这些连接可以被多个客户端共享和复用。创建连接池可以提高性能,因为它避免了每次请求都重新建立数据库连接。

   - `host: '127.0.0.1'`:数据库服务器的主机地址。这里是本地服务器。
   - `user: 'root'`:数据库用户名。
   - `port: '3306'`:数据库端口号。MySQL 的默认端口是 3306。
   - `password: 'root'`:数据库密码。
   - `database: 'test'`:要连接的数据库名称。

3. **导出连接池**:
   ```javascript
   module.exports = db;
   ```
   这行代码将连接池对象 `db` 导出,以便在其他模块中可以通过 `require` 方法导入并使用这个连接池。

使用这个连接池,你可以在其他模块中引入并使用它来执行数据库查询。例如:

```javascript
// 引入数据库连接池
const db = require('./path/to/this/module');

// 执行数据库查询
db.query('SELECT * FROM user', (err, results) => {
    if (err) {
        console.error('Error executing query:', err);
        return;
    }
    console.log('Query results:', results);
});
```

这种方式可以方便地管理和使用数据库连接,特别是在需要频繁访问数据库的应用中。

(2)index.js

const express = require('express');  
const app = express();  
const port = 3000; // 你可以选择任何未被占用的端口  
const db = require('./db')

// 设置中间件以允许跨域请求(可选,根据你的需求)  
app.use((req, res, next) => {  
  res.header("Access-Control-Allow-Origin", "*");  
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");  
  next();  
});  

//配置对外接口
app.get('/', (req, res) => {
  var sql = 'select * from user'
  db.query(sql, (err, data) => {
      if(err) {
          return res.send({
            status: 400,
            message: "查询失败"
          })
      } else{
        console.log('查询结果:', data)
		res.json(data); 
      }
  })
});

// 设置路由和响应  
/*
app.get('/', (req, res) => {  
  // 创建一个对象,其中包含你想要返回的数据  
  const data = [  
  { id: 1, name: 'Alice', age:18, email: 'alice@example.com' },  
  { id: 2, name: 'Bob', age:19, email: 'bob@example.com' },  
  // ...更多用户  
  ];  
  
  // 使用res.json()方法发送JSON响应  
  res.json(data);  
});  
*/
// 启动服务器  
app.listen(port, () => {  
  console.log(`Server is running on http://localhost:${port}`);  
});

2.补充小白知识

不懂就多看:/

  • 服务器端

    • 创建 Express 服务器,并设置数据库连接池。
    • 设置允许跨域请求的中间件。
    • 定义一个 GET 路由来查询数据库,并返回数据。
  • 客户端

    • 使用 Axios 在 Vue 组件中发送 HTTP 请求到服务器。
    • 获取数据并将其显示在页面上。

“使用这个连接池,你可以在其他模块中引入并使用它来执行数据库查询。”——其他模块是什么?

是server中的服务器端代码。

在这个上下文中,“其他模块”通常是指在你的 Node.js 项目中的其他 JavaScript 文件,而不是在 Vue 组件的 `.vue` 文件里。具体来说,这些其他模块通常是服务器端的代码,用于处理 HTTP 请求和数据库交互。

一个典型的项目结构可能是这样的:

```
project/
├── server/
│   ├── db.js        // 你提供的数据库连接池代码
│   ├── routes.js    // 定义API路由的模块
│   └── server.js    // 启动服务器的文件,我这里对应的就是
└── client/
    ├── src/
    │   ├── components/
    │   │   ├── YourComponent.vue   // 你的Vue组件
    │   ├── main.js                 // Vue项目入口文件
    │   └── ...                    // 其他前端文件
    └── package.json
```

在这个结构中,`server/` 文件夹包含服务器端的代码,而 `client/` 文件夹包含前端的 Vue 代码。

### 示例:在服务器端使用数据库连接池

假设你已经有一个 `server/db.js` 文件定义了数据库连接池,那么你可以在 `server/routes.js` 文件中引入并使用它:

```javascript
// server/routes.js
const express = require('express');
const db = require('./db'); // 引入数据库连接池

const router = express.Router();//这个routers.js的这段我没有用,其他的部分都被一起放在index.js里了,一起实现了“引入数据库连接池-根据需求设置跨域访问?-设置路由-(最终目的)启动服务器”

// 定义一个示例路由
router.get('/users', (req, res) => {
    db.query('SELECT * FROM user', (err, results) => {
        if (err) {
            return res.status(500).json({ error: err.message });
        }
        res.json(results);
    });
});

module.exports = router;
```

然后,在 `server/server.js` 文件中设置和启动 Express 服务器,并使用定义的路由:

```javascript
// server/server.js
const express = require('express');
const app = express();
const routes = require('./routes'); // 引入定义的路由

app.use('/api', routes); // 使用路由

const port = 3000;
app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});
```

### 在 Vue 组件中使用 API

在你的 Vue 组件中,你可以使用 Axios 发送 HTTP 请求到上述定义的 API:

```vue
<template>
  <div>
    <h2>Users</h2>
    <ul>
      <li v-for="user in users" :key="user.id">
        {{ user.name }} - {{ user.email }}
      </li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      users: []
    };
  },
  mounted() {
    axios.get('http://localhost:3000/api/users')
      .then(response => {
        this.users = response.data;
      })
      .catch(error => {
        console.error('Error fetching users:', error);
      });
  }
};
</script>
```

这样,通过分离前端和后端的逻辑,你可以更好地组织和管理代码,同时确保服务器端处理数据库交互,而前端通过 API 进行数据获取和展示。

3.

1)服务器端必须在监听中啊!!只有在监听中才可以运行项目看见后台数据。就是以下步骤:

项目/src/sserver/——cmd——node index.js命令,启动查看

正确监听显示:

其次,我发现我能用http://localhost:3000/api/users看见正确的JSON数据,但用http://localhost:3000不能,解决如下:

修改optionOne.vue:

export default {
  data() {
    return {
      users: []
    };
  },
  mounted() {
   // axios.get('http://localhost:3000/api/users')//服务端的信息
	axios.get('http://localhost:3000')//服务端的信息
      .then(response => {
        this.users = response.data;
      })
      .catch(error => {
        console.error('Error fetching users:', error);
      });
  }
};

4.如何加上login页面

先要在assets文件夹中加上:img是一开始登录进来的页面图片,和css文件夹

然后补充Login.vue,Login的路由器

最后就是调整之前的页面,分开App.vue(总的),做封装,把页面的左边划栏框做成一个单独的Bar.vue,然后要想每个页面都看见这个Bar,就要在每个文件.vue中加上对Bar.vue的引用。

示例:

optionTwo.vue:

<template>
  <el-main>
    <el-container>
      <Bar />
        {{msg}}
        <!-- 根据当前的路由显示内容 -->
        <router-view></router-view>
    </el-container>
  </el-main>
</template>

<script>
import Bar from './Bar.vue';

export default {
  name: 'optionTwo',
  components:{
		Bar
  },
  data () {
    return {
      msg: 'Option Two'
    }
  }
}
</script>

optionOne.vue:

  • 虽然<script>里面import了Bar,但是模块中也要用<Bar />
  • 注释掉了import axios因为这句话跟它同作用this.$http.get('/optionone').then(response => 。
  • 要想数据库中的数据正确显示在列名的后面,就要前两列名设置参数时设置width,而最后一列名不设置width。
<template>
  <el-main>
    <el-container>
      <Bar />
        <el-table :data="information">
          <el-table-column prop="users" label="Users" width="140" />
          <el-table-column prop="sex" label="Sex" width="140" />
          <el-table-column prop="mood" label="mood" />
        </el-table>
        <!-- 根据当前的路由显示内容 -->
        <router-view></router-view>
    </el-container>
  </el-main>
</template>

<script>
//import axios from 'axios';
import Bar from './Bar.vue';

export default {
  data() {
    return {
      information: []
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    getUserList() {
      this.$http.get('/optionone').then(response => {
        console.log(response.data);
        this.information = response.data;
      })
      .catch(error => {
        console.log(error);
      });
    }
  },
  // mounted() {
  //   axios.get('http://localhost:3000/api/users')
  //     .then(response => {
  //       this.users = response.data;
  //     })
  //     .catch(error => {
  //       console.error('Error fetching users:', error);
  //     });
  // },
  name: 'OptionOneComponent',
  components: {
    Bar
  }
};
</script>

<style>
.layout-container-demo .el-header {
  position: relative;
  background-color: var(--el-color-primary-light-7);
  color: var(--el-text-color-primary);
}
.layout-container-demo .el-main {
  padding: 0;
}
.layout-container-demo .toolbar {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  right: 20px;
}
</style>

当然,我可以为你解答这些问题:

### 1. 理解每个文件的作用和它们如何协同工作

**db.js (后端数据库配置文件)**
- 作用:创建并导出一个MySQL数据库连接池。
- 如何协同工作:供index.js使用以执行数据库操作。

**index.js (后端服务器主文件)**
- 作用:设置Express服务器,配置路由和中间件,处理API请求。
- 如何协同工作:使用db.js连接数据库,响应来自前端的请求。

**main.js (前端主文件)**
- 作用:创建Vue应用,配置Vue Router和axios,挂载应用。
- 如何协同工作:使用Element Plus和Vue Router增强用户界面和导航,axios用于与后端通信。

**index.js (Vue Router配置文件)**
- 作用:定义前端路由,指定不同路径对应的Vue组件。
- 如何协同工作:与main.js中的Vue实例集成,实现页面路由。

### 2. 演示如何启动后端和前端服务器

**启动后端服务器**:
- 运行`node index.js`来启动Express服务器。
- 确保MySQL服务正在运行。

**启动前端服务器**:
- 如果使用Vue CLI,运行`npm run serve`来启动热重载的开发服务器。
- 访问浏览器中的指定地址(通常是localhost和某个端口)来查看前端应用。

### 3. 展示前端页面和用户交互流程

- 用户打开应用,Vue Router将根据URL渲染对应的组件。
- 用户进行操作(如填写登录表单),数据通过表单提交到后端。
- 用户看到响应结果(登录成功或失败),并根据结果导航到不同页面。

### 4. 解释API请求和响应的过程

- 前端使用axios向后端发送HTTP请求。
- 后端Express服务器接收请求,执行数据库操作。
- 后端将数据库查询结果或错误信息作为响应发送回前端。
- 前端接收响应,并根据响应更新页面状态或显示信息。

### 5. 讨论项目中使用的关键技术

- **Vue Router**:管理前端路由,实现单页面应用中的页面导航。
- **axios**:用于从前端向后端发送HTTP请求和处理响应。
- **Express**:Node.js的Web应用框架,用于创建后端服务器和处理API请求。
- **MySQL**:关系型数据库管理系统,用于存储和查询数据。

### 6. 准备一些常见问题的答案

**如何处理CORS?**
- 使用cors中间件允许特定的外部域访问API。

**用户认证如何实现?**
- 后端API可以检查请求中的认证信息(如JWT tokens)来验证用户身份。

**数据安全如何保证?**
- 使用HTTPS加密传输数据。
- 对用户密码进行哈希处理后存储。
- 验证所有用户输入以防止SQL注入等攻击。

通过上述解答,你应该能够对项目的工作原理和实现过程有一个清晰的理解,从而准备好答辩。
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值