1.TS泛型的使用及如果请求接口不时REST API,如何使用json-server自定义请求
import React, { FormEvent } from 'react'
const apiUrl = process.env.REACT_APP_API_URL
export const LoginScreen = () => {
// 定义login函数
const login =(param:{username:string,password:string}) => {
fetch(`${apiUrl}/login`,{
method: 'POST',
headers: {
'Content-type':'application/json'
},
body: JSON.stringify(param)
}).then(async response => {
if (response.ok) {
}
})
}
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault()
const username = (event.currentTarget.elements[0] as HTMLInputElement).value
const password = (event.currentTarget.elements[1] as HTMLInputElement).value
login({username,password})
}
return <form onSubmit={handleSubmit} >
<div>
<label htmlFor="username">用户名</label>
<input type="text" id={'username'} />
</div>
<div>
<label htmlFor="password">密码</label>
<input type="password" id={'password'} />
</div>
<button type={"submit"}>登录</button>
</form>
}
2.自定义json-server
module.exports = (req, res, next) => {
if (req.method === 'POST' && req.path === '/login') {
if (req.body.username === 'cloudgaps' && req.body.password === '123456') {
return res.status(200).json({
user: {
token: 'cloud'
}
})
} else {
return res.status(400).json({ message: '用户名或密码错误' })
}
}
next()
}
引入:
"json-server": "json-server __json_server_mock__/db.json --watch --port 3001 --middleware ./__json_server_mock__/middleware.js"