reactjs - 在反应中获取 API
问题描述
我是 React 的新手,我被卡住了。我正在尝试制作一个注册页面,其中包含文本框:姓名、电话号码、电子邮件、密码。
我想要的是,当我点击登录按钮时,所有这些详细信息都应该通过 POST 发送到我的 API,并获取并存储响应。
接口:
http://localhost:5000/api/users/signup
方法:
POST
以这种方式发送对我的 api 的请求:
content-type: application/json
{
"name": "Devanshh Shrivastvaaaa",
"phoneNumber":"982964XXX8",
"email": "devannnnnshh;@ccc.in",
"password": "1234566788"
}
任何人都可以使用代码向我解释如何在单击注册和获取响应时将此数据发送到我的 api
解决方案
不需要使用任何第三方库,只需使用 Javascript fetch API
// Example POST method implementation:
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
postData('https://example.com/answer', { answer: 42 })
.then(data => {
console.log(data); // JSON data parsed by `data.json()` call
});
推荐阅读
- ios - 过度释放字典中导致 EXC_BAD_ACCESS 错误的对象?
- javascript - 将输入值添加到 localStorage
- rules - Snort 规则无法捕获从 Internet 下载的 JPG 文件
- php - 发送btc api币库?
- python - 不同准则的两次连续排序
- variables - Golang中不同的变量类型声明
- php - PHP preg_replace 适用于所有类型的年份格式(YYYY、YYYY-YYYY、YYYY - YYYY)
- api - 亚马逊商城网络服务创建入库货件 NOT_ELIGIBLE_FC_FOR_ITEM,有什么问题?
- javascript - 以后端期望的特定格式重构 JS 数组
- c# - UWP MediaPlayerElement 流超时