【问题标题】:how to add alert message in fetch request如何在获取请求中添加警报消息
【发布时间】:2022-07-13 11:11:14
【问题描述】:
In the Fetch request the need to add the alert message which should display in front end if the message response is ok status else also add alert message as error.

function LoginUser() {
    const requestOptions = {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' ,
                 'Accept': 'application/json'},
      body: JSON.stringify({ "username":username, "password":password })
      
    };
     fetch('http://localhost:8080/abc', requestOptions)
     .then((response)=>{
       if(response.status==200){
          console.log('succesfull');
 }
       
         else{
          throw new Error('Invalid credentials');
         }
       })
       .catch((err)=>{
         console.log(err);
       });
}    

登录

如果响应正常则显示成功否则无效
如何在获取请求中传递警报消息

【问题讨论】:

  • 你可以使用alert代替console.log或者使用第三方包如react-toast-notifications
  • 好的,在获取请求中添加了警报消息,当响应为 200 时,成功在网页和控制台上完全显示警报消息,但是当错误时,它显示在控制台中但不显示在网页中, then 和 catch 的 fetch 请求语法有没有问题。

标签: reactjs react-hooks


【解决方案1】:

您可以添加警报而不是控制台日志。 因此,您可以对 if 语句执行此操作。

if(response.status==200){
    alert('succesfull');
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 2022-12-11
    相关资源
    最近更新 更多