1.测试mock的简单使用
首先我们在mock文件夹创建一个文件(文件名随便取)
写上这样一段代码,代表Get请求
在登录组件Login中发起请求
启动项目,并在项目的url地址输入/users,就可以看到
2.登录案例
api.js
export default {
// "Get /users":{name:"rebecca",age:23}
'POST /users/login': (req, res) => {
//前端传来的内容
console.log(req.body);
// 设置响应体 成功ok=1,失败则ok=0
// 加上限制条件
if (req.body.username === 'rebecca' && req.body.password === '123') {
res.send({ ok: 1 });
} else {
res.send({ ok: 0 });
}
},
};
Login.tsx
import React, { useEffect, useState } from 'react';
import { useHistory } from 'umi';
export default function Login() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const history = useHistory();
// useEffect(() => {
// fetch('/users')
// .then((res) => res.json())
// .then((res) => console.log(res));
// }, []);
return (
<div>
<input
type="text"
onChange={(event) => {
setUsername(event.target.value);
}}
/>
<input
type="password"
onChange={(event) => {
setPassword(event.target.value);
}}
/>
{username}-{password}
<button
onClick={() => {
fetch('/users/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json', //json格式
},
body: JSON.stringify({
// username:username,
// password:password
//简写
username,
password,
}),
})
.then((res) => res.json())
.then((res) => {
console.log(res);
if (res.ok) {//ok为1
localStorage.setItem('token', username);
history.push('/center');
} else {//ok为0
alert('用户名与密码不匹配!');
}
});
}}
>
点击登录
</button>
</div>
);
}
3.反向代理——跨域
猫眼电影网有跨域限制,我们请求猫眼的数据
在Comingsoon组件中发起请求
我们要请求的网址是:
https://i.maoyan.com/api/mmdb/movie/v3/list/hot.json?ct=%E6%9D%AD%E5%B7%9E&ci=50&channelId=4
将网址拆分开
.umirc.ts
Comingsoon.ts