【问题标题】:Fetching an API in react在反应中获取 API
【发布时间】:2020-08-01 17:39:13
【问题描述】:

我是 React 新手,我被卡住了。我正在尝试制作一个注册页面,其中包含文本框:姓名、电话号码、电子邮件、密码。

我想要的是,当我点击登录按钮时,所有这些详细信息都应该通过 POST 发送到我的 API,并获取并存储响应。

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

【问题讨论】:

标签: reactjs api


【解决方案1】:

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

Source: Mozilla MDN

【讨论】:

    【解决方案2】:

    需要安装axios或者取axios好axios

    axios.post('http://localhost:5000/api/users/signup', {
        name: "Devanshh Shrivastvaaaa",
         phoneNumber":"982964XXX8",
         email: "devannnnnshh;@ccc.in",
         password: "1234566788"
    })
    .then((response) => {
      console.log(response);
    }, (error) => {
      console.log(error);
    });
    

    还要检查for further

    【讨论】:

    • 我是新来的反应,请您使用代码解释如何发送标头,以及单击注册按钮后如何获取数据。
    • 我是新来的反应,请您使用代码解释如何发送标头,以及单击注册按钮后如何获取数据。
    • 在响应控制台中,您可以从服务器 const options = { headers: {'X-Custom-Header': 'value'} }; axios.post('/save', { a: 10 }, options); 获取数据,请参阅我提到的链接,您可以找到东西
    猜你喜欢
    • 2018-12-14
    • 2018-06-10
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 2020-10-06
    • 1970-01-01
    相关资源
    最近更新 更多