Axios createError.js:16未捕获(承诺)错误:请求失败,状态码为500

时间:2020-07-01 04:08:37

标签: node.js reactjs axios

你好,我正在开发一个React-Node Js应用程序,并将一个组件类迁移到一个功能组件,现在我遇到了问题:createError.js:16 Uncaught (in promise) Error: Request failed with status code 500同样的方法在组件类中也能很好地工作。接下来是我的react组件的代码:

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import { useState } from "react";
import axios from "axios";
import TextField from "@material-ui/core/TextField";
import Button from "@material-ui/core/Button";
import Typography from "@material-ui/core/Typography";

const useStyles = makeStyles((theme) => ({
  root: {
    "& > *": {
      margin: theme.spacing(1),
      width: "25ch",
    },
  },
}));

export default function BasicTextFields(props) {
  const classes = useStyles();
  const [collection, setCollection] = useState("");
  const [field, setField] = useState("");
  const [integrationName, setIntegrationName] = useState("");
  const [total, setTotal] = useState("");

  function handleChange(evt, field) {
    setField(evt.target.value);
    console.log("new value", evt.target.value);
  }

  function handleSubmit(event) {
    console.log("Event delete:" + event);
    var params = new URLSearchParams();
    params.append("collection", collection);
    params.append("field", field);
    params.append("integrationName", integrationName);
    var request = {
      params: params,
    };

    console.log("request: 127.0.0.1:" + request);

    axios.delete(`http://127.0.0.1:8081/firestore/`, request).then((res) => {
      console.log("react1: ", res);
      console.log("react2: ", res.data);
      this.setState({ total: res.data });
    });
  }

  function handleSubmitCount(event) {
    console.log("...count...");
    var params = new URLSearchParams();
    params.append("collection", collection);
    params.append("field", field);
    params.append("integrationName", integrationName);
    var request = {
      params: params,
    };

    console.log("request 127.0.0.1:" + request);
    console.log("BACKEND_HOST:", process.env);
    axios.get(`http://127.0.0.1:8081/firestore/`, request).then((res) => {
      this.setState({ total: res.data });
    });
  }

  return (
    <span>
      <form className={classes.root} noValidate autoComplete="off">
        <TextField
          name="collection"
          onChange={(e) => setCollection(e.target.value)}
          helperText="Collection"
          variant="outlined"
          required
          margin="dense"
        />
        <TextField
          name="field"
          onChange={(e) => setCollection(e.target.value)}
          helperText="Field"
          variant="outlined"
          required
          margin="dense"
        />

        <TextField
          name="value"
          onChange={(e) => setCollection(e.target.value)}
          helperText="Value"
          variant="outlined"
          required
          margin="dense"
        />
        <br />
        <Button
          variant="contained"
          color="primary"
          onClick={(e) => handleSubmit(e)}
          disableElevation
          type="button"
        >
          Delete Registers
        </Button>
        <Button
          variant="contained"
          color="primary"
          onClick={(e) => handleSubmitCount(e)}
          disableElevation
          type="button"
        >
          Count Registers
        </Button>

        <br />
        <br />
        <Typography variant="h6" gutterBottom>
          {total}
        </Typography>
      </form>
    </span>
  );
}

当我单击按钮并使用handleSubmitCount方法时,由于某种原因,它没有调用axios请求,而引发了前面提到的问题,我得到了错误消息。

有什么想法吗?

4 个答案:

答案 0 :(得分:0)

请尝试这种方式

function requestObject(url,method, params) {
    let configObject = {
        "url": url,
        "method": method,
        "params": params
        
    }
    return configObject
}

 function handleSubmit(event) {
        console.log("Event delete:" + event);
       let data= {
      "collection": collection, "field" : field, 
      "integrationName":integrationName
};
let configObejct = requestObject("http://127.0.0.1:8081/firestore/", "delete", data);
axios.request(configObejct).then((res) => {
          console.log("react1: ", res);
          console.log("react2: ", res.data);
          this.setState({ total: res.data });
        });
      }

答案 1 :(得分:0)

500是服务器错误。尝试检查您的错误:

axios.get("http://127.0.0.1:8081/firestore/", request).then((res) => {
  this.setState({ total: res.data });
}).catch(error => console.error(error));

答案 2 :(得分:0)

检查Axios文档,您会发现delete方法没有收到正文参数,这是您在该冒号之后发送的sendind。请求必须仅具有url参数和选项/配置参数(可选)。

https://github.com/axios/axios/blob/master/README.md#axiosdeleteurl-config

我建议您这样发出请求:

axios.delete(`http://127.0.0.1:8081/firestore/${params.toString()}`).then(callback);

由于请求仅包含您的参数,因此不再需要此对象。

请记住,这些参数属于查询字符串参数类型,这就是URLSearchParams接口上的目的。

https://developer.mozilla.org/es/docs/Web/API/URLSearchParams

祝你好运!

答案 3 :(得分:0)

似乎已经过去了几个月,但现在已经过去了......(我也遇到了同样的问题。

您很可能会收到一个 HTTP 错误代码,而 Axios 拒绝了该承诺。

您需要捕获它并从服务器(如果有)获取消息。

axios.get(`http://127.0.0.1:8081/firestore/`, request)
    .then((res) => {
        this.setState({ total: res.data });
    })
    .catch((error) => {
        // here you will have access to error.response
        console.log(error.response)
    });