在云开发平台使创建应用使用自己的对应数据库实现一个注册和登陆系统
步骤1
1.阿里云平台,创建应用实验室-web-Midway Serverless OTS数据库示例
2.进入云IDE,安装依赖,在终端输入
npm i
3.创建阿里云OTS表格存储
网站 https://www.aliyun.com/product/ots
进入管控台,点击之前day5创建的实例less
创建数据库表,如图
配置环境变量,在应用管理界面刚刚创建的应用,点击应用配置,输入day5中的公网ip和相关信息
4.进入CloudIDE,修改代码
(1) f.yml
register:
handler: user.register
events:
- apigw:
path: /api/register
login:
handler: user.login
events:
- apigw:
path: /api/login
<link href="https://cdn.bootcdn.net/ajax/libs/tailwindcss/1.6.2/tailwind.min.css" rel="stylesheet">
import React, { useEffect, useState } from 'react'
import ReactDOM from 'react-dom';
import './index.css';
import 'todomvc-app-css/index.css'
import { AddTodoEntry } from './components/entry'
import Footer from './components/footer'
import Todos from './components/todos'
//修改开始
export default function App() {
const [name, setName] = useState('')
const [password, setPassword] = useState('')
const handleRegister = () => {
console.log('name is', name)
console.log('password is', password)
fetch(`/api/register?name=${name}&password=${password}`)
.then(resp => resp.json())
.then(resp => {
if (resp.success === true) {
alert('注册成功')
}
})
}
const handleLogin = () => {
console.log('name is', name)
console.log('password is', password)
fetch(`/api/login?name=${name}&password=${password}`)
.then(resp => resp.json())
.then(resp => {
if (resp.success === true) {
alert(`登录成功,用户名:${resp.user.name}`)
} else {
alert(`登录失败,提示信息:${resp.message}`)
}
})
}
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
<div className="max-w-md w-full">
<div>
<img className="mx-auto h-12 w-auto" src="https://tailwindui.com/img/logos/workflow-mark-on-white.svg" alt="Workflow" />
<h2 className="mt-6 text-center text-3xl leading-9 font-extrabold text-gray-900">
注册或者登录
</h2>
</div>
<form className="mt-8" action="#" method="POST">
<input type="hidden" name="remember" defaultValue="true" />
<div className="rounded-md shadow-sm">
<div>
<input
onChange={e => {
console.log('当前输入的账号是:', e.target.value)
setName(e.target.value)
}}
aria-label="Email address" name="email" type="email" required className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:shadow-outline-blue focus:border-blue-300 focus:z-10 sm:text-sm sm:leading-5" placeholder="Email address" />
</div>
<div className="-mt-px">
<input
onChange={e => {
setPassword(e.target.value)
}}
aria-label="Password" name="password" type="password" required className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:shadow-outline-blue focus:border-blue-300 focus:z-10 sm:text-sm sm:leading-5" placeholder="Password" />
</div>
</div>
<div className="mt-6">
<button type="button" onClick={handleRegister} className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm leading-5 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-500 focus:outline-none focus:border-indigo-700 focus:shadow-outline-indigo active:bg-indigo-700 transition duration-150 ease-in-out">
<span className="absolute left-0 inset-y-0 flex items-center pl-3">
</span>
注册
</button>
</div>
<div className="mt-6">
<button type="button" onClick={handleLogin} className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm leading-5 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-500 focus:outline-none focus:border-indigo-700 focus:shadow-outline-indigo active:bg-indigo-700 transition duration-150 ease-in-out">
<span className="absolute left-0 inset-y-0 flex items-center pl-3">
</span>
登录
</button>
</div>
</form>
</div>
</div>
)
}//修改结束
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
(4.)在src/apis新建user.ts
import { Func, Inject, Provide } from '@midwayjs/decorator';
import TableStore from 'tablestore';
import format from 'otswhere/format';
@Provide()
export class UserService {
@Inject()
ctx;
@Inject()
tb;
@Func('user.login')
async login() {
const { name, password } = this.ctx.query;
const params = {
tableName: 'user',
direction: TableStore.Direction.BACKWARD,
inclusiveStartPrimaryKey: [{ id: TableStore.INF_MAX }],
exclusiveEndPrimaryKey: [{ id: TableStore.INF_MIN }]
};
return new Promise(resolve => {
this.tb.getRange(params, (_, data) => {
const rows = format.rows(data, { email: true });
const userExists = rows.list.findIndex(user => user.name === name) !== -1
if (!userExists) {
resolve({
success: false,
message: '用户不存在'
})
return
}
const user = rows.list.find(user => user.name === name);
if (user.password !== password) {
resolve({
success: false,
message: '密码不正确'
})
return
}
resolve({
success: true,
user
});
});
})
}
@Func('user.register')
async register() {
const { name, password } = this.ctx.query;
const params = {
tableName: "user",
condition: new TableStore.Condition(TableStore.RowExistenceExpectation.IGNORE, null),
primaryKey: [
{ id: `${Date.now()}-${Math.random()}` }
],
attributeColumns: [
{ name },
{ password },
{ status: '1' }
]
};
return new Promise(resolve => {
this.tb.putRow(params, async function (err, data) {
if (err) {
resolve({
success: false,
errmsg: err.message
});
} else {
resolve({
success: true,
data
});
}
});
});
}
}
5.启动开发服务
在终端输入
npm run dev