写一个微信小程序的常见登录页面,登录输入●email :用户邮箱 ●password:用户密码接口路径:/login 接口说明: 登录时在请求体中携带邮箱和密码,如果登录成功会在cookie中添加一个ticket字段作为身份令牌,在cookie有效期间再去访问网站资源就不会要求重新登录。 请求方式:post
时间: 2024-02-21 20:57:18 浏览: 23
好的,这是一个常见的微信小程序登录页面的代码示例:
```
<view class="container">
<view class="title">用户登录</view>
<form bindsubmit="login" class="form">
<view class="form-item">
<view class="form-item-label">邮箱:</view>
<input name="email" type="text" placeholder="请输入邮箱" class="form-item-input" />
</view>
<view class="form-item">
<view class="form-item-label">密码:</view>
<input name="password" type="password" placeholder="请输入密码" class="form-item-input" />
</view>
<button form-type="submit" class="login-button">登录</button>
</form>
</view>
```
其中,`form` 标签绑定了 `login` 函数,当用户点击登录按钮时会触发该函数,向服务器发送 POST 请求以登录。
下面是 `login` 函数的实现:
```
Page({
login: function(event) {
wx.request({
url: '/login',
method: 'POST',
data: {
email: event.detail.value.email,
password: event.detail.value.password
},
success: function(response) {
if (response.statusCode === 200) {
wx.setStorageSync('ticket', response.cookies[0]) // 将 ticket 保存到本地缓存中
wx.navigateTo({
url: '/pages/index/index' // 登录成功后跳转到首页
})
} else {
wx.showToast({
title: '登录失败',
icon: 'none'
})
}
},
fail: function(error) {
wx.showToast({
title: '登录失败',
icon: 'none'
})
}
})
}
})
```
在 `login` 函数中,我们使用 `wx.request` 方法向服务器发送 POST 请求,请求路径为 `/login`,请求体中包含用户输入的邮箱和密码。如果登录成功,服务器会在响应头中返回一个 `Set-Cookie` 字段,其中包含一个名为 `ticket` 的身份令牌;我们将该令牌保存到本地缓存中,以便之后访问网站资源时可以携带该令牌,避免重新登录。
如果登录失败,我们会弹出一个提示框告诉用户登录失败。
希望这个代码示例对你有所帮助!