【问题标题】:Axios createError.js:16 Uncaught (in promise) Error: Request failed with status code 500Axios createError.js:16 Uncaught (in promise) 错误:请求失败,状态码 500
【发布时间】:2020-10-21 11:18:02
【问题描述】:

您好,我正在开发一个 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 请求,而是抛出了前面提到的问题。

有什么想法吗?

【问题讨论】:

    标签: node.js reactjs axios


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      检查 Axios 文档,您会发现 delete 方法没有收到您在冒号后发送的正文参数。请求只能有一个 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】:

        请试试这个方法

        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 });
                });
              }
        

        【讨论】:

        • 周二问题是一样的。
        • 对不起,我没有工作。我得到了同样的 500 代码错误。
        【解决方案4】:

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

        您很可能收到 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)
            });
        

        【讨论】:

          猜你喜欢
          • 2021-04-12
          • 1970-01-01
          • 1970-01-01
          • 2021-09-15
          • 2021-03-11
          • 2018-11-29
          • 2021-06-11
          • 2020-05-29
          • 1970-01-01
          相关资源
          最近更新 更多