使用axios时从服务器获取json错误响应

时间:2020-10-24 21:50:48

标签: javascript json reactjs axios

<!doctype html>
<html class="no-js" lang="en">

<head>
  <meta charset="UTF-8">
  <title>Home page</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="">

  <meta property="og:title" content="">
  <meta property="og:type" content="">
  <meta property="og:url" content="">
  <meta property="og:image" content="">

  <link rel="manifest" href="site.webmanifest">
  <link rel="apple-touch-icon" href="icon.png">
  <!-- Place favicon.ico in the root directory -->

  <meta name="theme-color" content="#fafafa">
</head>

<body>

<?php include "html/header.html"; ?>

<div class="content">
  <main>
    <?php include "html/indexCarousal.html";?>
    <?php include "html/googleMapsAPI.html";?>
  </main>
  <?php include "html/footer.html";?>
</div>


<script src="js/vendor/modernizr-3.11.2.min.js"></script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>

</body>
</html>
<script>window.addEventListener('DOMContentLoaded', function() {$("#home").removeClass("navnotactive").addClass("navactive");});</script>

我正在使用这段代码将POST请求发送到我的react应用程序中的后端服务器,但是无法获取服务器提示的json错误,这是我得到的:-

Axios.post('http://localhost:3001/signup',
        {
            name:name,
            email:email,
            password:password
        })
        .then((res)=>{
            if(res.data){
                M.toast({html: 'Response successfully recorded!'}) //giving the message
            }
            console.log(res);
        })

如何获取服务器给出的json错误以在前端处理错误?

1 个答案:

答案 0 :(得分:-1)

您需要使用.catch

Axios.post('http://localhost:3001/signup',
{
    name:name,
    email:email,
    password:password
})
.then((res)=>{
    if(res.data){
        M.toast({html: 'Response successfully recorded!'}) //giving the message
    }
    console.log(res);
}).catch((err) => console.log(err));

.then表示请求成功。

.catch表示请求失败。