使用fetch 编写代码实现登录和注册接口
时间: 2024-05-09 13:18:24 浏览: 10
我可以为你展示一段使用fetch编写的登录和注册接口的示例代码,请参考下面的代码:
注册:
```javascript
const register = (email, password) => {
return fetch('/api/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ email, password })
})
.then(res => res.json())
.catch(err => console.error(err))
}
```
登录:
```javascript
const login = (email, password) => {
return fetch('/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ email, password })
})
.then(res => res.json())
.catch(err => console.error(err))
}
```
在这个示例代码中,我们使用fetch API来发送POST请求,向服务器发送登录和注册请求,并将用户的email和password作为参数传递。服务器将返回JSON格式的响应,如果请求成功,则可以提取响应中的数据。
请注意,示例代码只是一种演示方式,实际上您在实现登录和注册接口时应该考虑更多的安全措施,例如添加验证和授权。