前后端交互

# Students-system开发步骤

## 项目初始化

新建文件夹,命名为`students-system`,注意这里的命名不得为中文或其他特殊字符

```shell
npm init -y
```

## 安装包

```shell
npm i jquery express express-art-template
```

## 新建文件夹

新建public,views文件夹,public下新建img,js,css文件夹,目录如下:

```
student-system
    node_modules
    public
        img
        css
        js
    views
    package.json
    ...
```

## 新建服务

在students-system文件夹下新建`server.js`

```js
const express=require('express')

const app = express()

//配置express-art-template,才可以render html
app.engine('html',require('express-art-template'))

app.get('/',(req,res) =>{
    res.render('login.html')
})

app.listen(3000,() => console.log('app listening on http://localhost:3000 '))
```

当用户get   / 时,就会渲染login.html

开通了3000端口号。

> ip地址是链接到网络上的某台计算机
>
> 端口号是识别到该计算机上的某个软件

## 新建页面

在`views`文件夹下,新建`login.html`

```html
<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
        }

        .container {
            max-width: 400px;
            margin: 0 auto;
            padding: 20px;
            background-color: #ffffff;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        h1 {
            text-align: center;
            margin-bottom: 20px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            font-weight: bold;
            margin-bottom: 5px;
        }

        input[type="email"],
        input[type="password"] {
            width: 100%;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        button {
            display: block;
            width: 100%;
            padding: 10px;
            background-color: #4caf50;
            color: #ffffff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        button:hover {
            background-color: #45a049;
        }

        .text-center {
            text-align: center;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>Login</h1>
    <form>
        <div class="form-group">
            <label for="email">Email:</label>
            <input type="email" id="email" name="email" required>
        </div>
        <div class="form-group">
            <label for="password">Password:</label>
            <input type="password" id="password" name="password" required>
        </div>
        <div class="text-center">
            <button type="submit">Login</button>
        </div>
    </form>
</div>
</body>
</html>


```

此时,用户在浏览器进入 [Login](http://localhost:3000/)即可打开我们的登录界面。

## 登录功能开发

### 传统的表单登录

表单登录,需要在form表单里,指定action和method,action是路径,method是方法,方法一般分为get和post

get用于保密级别低,长度短的信息(get会把请求写道url里面,受到url长度影响,信息的长度不能无限长)

post用于保密级别高(比如密码等),长度长的信息

> 表单登录,一定伴随着整个页面的重新跳转或刷新

在login.html,为表单指定路径和方法

```html
 <form action='/login' method='post'>
    ·······
 </form>
```

在后端server.js 里配置相应请求信息

```js
app.post('/login',(req,res) =>{
    console.log(req.body)
    if (req.body.email==='admin@qq.com'&&req.body.password==='admin'){
        res.render('main.html')
    }else{
        res.render('error.html')
    }
})
```

如果想要在后端使用req.body来获取post来的信息,比如在后端配置body-parser,现在新版本的express已经内置了body-parser,不需要额外安装,直接配置即可

```js
//配置body-parser
app.use(express.urlencoded({ extended:false}))
app.use(express.json())
```

如此,当用户输入正确账号和密码时,就可以跳转到main.html,如果错误账号或密码,则会跳转到error.html

error.html里可以配置错误信息,并且几秒后跳转回登录界面

### ajax局部刷新登录

由于表单登录,伴随着整个页面的刷新,带来白屏问题,等待,跳转等问题,非常不方便,而且提示信息是在错误页面上需要跳转来,跳转去

```html
 <form>
    ·······
 </form>
```

form表单里的action和method此时已经无用,删除掉

引入jQuery

```html
<script src="../node_modules/jquery/dist/jquery.js"></script>
```

打开localhost:3000发现,jQuery并没有被加载上,因为此时jQuery存在于服务器中的node_modules文件夹中,后端服务器的文件不允许前端随意查看,我们需要开放静态文件权限给前端,public和node_modulse两个文件夹

```js
/开放node_modules,public两个文件夹的权限,允许用户查看
app.use('/public', express.static('public'))
app.use('/bbb', express.static('node_modules'))
//前面的/aaa,/bbb是随便起名,可以对后端文件夹配置有一定的隐藏,防止被黑
```

此时,前端对于jQuery的引入,也可以改成下面形式,以隐藏真实后端文件夹目录

```html
<script src="/bbb/jquery/dist/jquery.js"></script>
```

配置前端jQuery ajax,向后端发起请求,如果账号密码正确,则跳转到新页面main.html,如果账号密码错误,则跳出提示

```html
<script>
   $('form').on('submit', function(event){
       event.preventDefault()//取消默认submit提交事件
       $.ajax({
           url:'/login',
           method: 'POST',
           data:{//向后端提交的数据
               email: $('#email').val(),
               password: $('#password').val()
           },
           success: function(data){//提交成功,要执行的函数,data就是后端回来的信息
               console.log(data)
               if (data.success){
                   window.location.href='/main.html'
               }else{
                    alert('账号或密码错误')
               }
           },
           error: function(){//如果受到网络原因或其他不确定因素的影响,导致请求失败执行的函数
               console.log('Something went wrong')
           }
       })
   })

</script>
```

后端对于post   /login的请求修改如下:

```js
app.post('/login',(req,res) =>{
    console.log(req.body)
    if (req.body.email==='admin@qq.com'&&req.body.password==='admin'){
        // res.render('main.html')
        res.send({success:true})
    }else{
        res.send({success:false})
    }
})
```

![image-20230615160632362](C:\Users\lvmen\AppData\Roaming\Typora\typora-user-images\image-20230615160632362.png)
posted @ 2023-06-30 10:14  曾像夜那么黑  阅读(23)  评论(0)    收藏  举报