首页 > 解决方案 > 在反应中获取 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

标签: reactjsapi

解决方案


不需要使用任何第三方库,只需使用 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
  });

资料来源:Mozilla MDN


推荐阅读