formik:发布URL/薪金量表400(不良要求)

发布于 2025-02-04 17:34:45 字数 6844 浏览 2 评论 0原文

我有这个项目,这是一个经营一家承包公司的项目,我正在尝试创建一个接口以允许管理员创建工资量表,这就是Swagger上的请求like:

,事实证明,我有各种各样的对象。

为此,我使用了一个Formik并将数据发送到后端,

但我得到了一个错误:

POST https://ite-ria.herokuapp.com/api/v1/salary-scales 400 (Bad Request)

此外,数据不填充数据,

这是浏览器中的网络的样子:

​/I.sstatic.net/pclsg.png“ alt =“在此处输入图像描述”>

如何解决问题?

file1.js:

import React, { useState } from "react";
import TextField from "@material-ui/core/TextField";
import Grid from "@material-ui/core/Grid";
import { makeStyles } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";
// import { addInvoice } from "../../../store/invoiceSlice";
import { motion } from "framer-motion";
import { useDispatch } from "react-redux";
import "react-datepicker/dist/react-datepicker.css";
import Slide from "@material-ui/core/Slide";
import { useSnackbar } from "notistack";
import { getJobs, addSalaryScale } from "../../store/salaryScaleSlice";
import { useEffect } from "react";
import InputAdornment from "@material-ui/core/InputAdornment";
import WorkOutlineOutlinedIcon from "@material-ui/icons/WorkOutlineOutlined";
import Input from "@material-ui/core/Input";
import AccountTreeOutlinedIcon from "@material-ui/icons/AccountTreeOutlined";
import { FieldArray, Field, Form, Formik } from "formik";
import { Card, CardContent } from "@material-ui/core";
import Autocomplete from "@material-ui/lab/Autocomplete";
import PostAddIcon from "@material-ui/icons/PostAdd";

const useStyles = makeStyles((theme) => ({
  root: {
    "& > *": {
      margin: theme.spacing(1),
    },
  },
  input: {
    display: "none",
  },
  button: {
    margin: theme.spacing(1),
    // padding: theme.spacing(4),
  },
}));

function ShippingTab(props) {
  const dispatch = useDispatch();
  const classes = useStyles();
  // const [amount, setAmount] = useState("");

  const [jobs, setJobs] = useState([]);
  // const [jobId, setJobId] = useState(0);

  // const [employeeLevel, setEmployeeLevel] = useState("");

  const { enqueueSnackbar, closeSnackbar } = useSnackbar();

  const handleCreateInvoiceMessageClick = () => {
    enqueueSnackbar(
      "Invoice created successfully",
      { variant: "success" },
      {
        anchorOrigin: {
          vertical: "top",
          horizontal: "right",
        },
      },
      { TransitionComponent: Slide }
    );
  };
  const handleAmountChange = (event) => {
    setAmount(event.target.value);
  };

  useEffect(() => {
    getJobs().then((response) => {
      console.log("jobs response in approve: ", response);
      // setJobs(response);
    });
  }, []);

  return (
    <Card>
      <CardContent>
        <Formik
          initialValues={{
            entities: [{ jobId: 0, amount: 0, employeeLevel: " " }],
          }}
          onSubmit={async (values) => {
            console.log("values: ", values);
            return dispatch(addSalaryScale(values));
          }}
        >
          {({ values, isSubmitting }) => (
            <Form autoComplete="off">
              <Grid container>
                <Grid item>
                  <FieldArray name="entities">
                    {({ push, remove, Formik }) => (
                      <React.Fragment>
                        {values?.entities.map((_, index) => (
                          <Grid container item key={index}>
                            <Grid item>
                              <Field
                                name={`entities[${index}].jobId`}
                                id="entities.jobId"
                                component={TextField}
                                label="JobId"
                              />
                            </Grid>

                            <Grid item>
                              <Field
                                name={`entities[${index}].amount`}
                                id="entities.amount"
                                component={TextField}
                                type="number"
                                label="amount"
                              />
                            </Grid>

                            <Grid item>
                              <Field
                                name={`entities[${index}].employeeLevel`}
                                id="entities.employeeLevel"
                                component={TextField}
                                label="employeeLevel"
                              />
                            </Grid>

                            <Grid item>
                              <Button onClick={() => remove(index)}>
                                Delete
                              </Button>
                            </Grid>
                          </Grid>
                        ))}

                        <Grid item>
                          <Button
                            onClick={() =>
                              push({ jobId: 0, amount: 0, employeeLevel: "" })
                            }
                          >
                            Add
                          </Button>
                        </Grid>
                      </React.Fragment>
                    )}
                  </FieldArray>
                </Grid>
              </Grid>

              <pre>{JSON.stringify({ values }, null, 4)}</pre>
              <button type="submit">Submit</button>
            </Form>
          )}
        </Formik>
      </CardContent>
    </Card>
  );
}

export default ShippingTab;

salaryscaleslice.js:

export const addSalaryScale = createAsyncThunk(
  "salaryScalesApp/salaryScale/addSalaryScale",
  async (salaryScale, { dispatch, getState }) => {
    console.log('salary Scale: ', salaryScale)
    const response = await axios.post("/salary-scales", salaryScale);
    const data = await response.data.data;
    console.log("Hi I am Here in add new Job: ", data);
    dispatch(getSalaryScales());

    return data;
  }
);

I have this project and it is a project to run a contracting company, and I am trying to create an interface in order to allow the admin to create a salary scale, and this is what the requestlooks like on Swagger:

enter image description here

And as it turns out, I have array of Objects.

And for that, I used a formik and sent the data to the backend

But I got this error:

POST https://ite-ria.herokuapp.com/api/v1/salary-scales 400 (Bad Request)

In addition, the data is not filled with data

This is what the network looks like in the browser:

enter image description here

enter image description here

enter image description here

enter image description here

How can i solve the problem?

file1.js:

import React, { useState } from "react";
import TextField from "@material-ui/core/TextField";
import Grid from "@material-ui/core/Grid";
import { makeStyles } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";
// import { addInvoice } from "../../../store/invoiceSlice";
import { motion } from "framer-motion";
import { useDispatch } from "react-redux";
import "react-datepicker/dist/react-datepicker.css";
import Slide from "@material-ui/core/Slide";
import { useSnackbar } from "notistack";
import { getJobs, addSalaryScale } from "../../store/salaryScaleSlice";
import { useEffect } from "react";
import InputAdornment from "@material-ui/core/InputAdornment";
import WorkOutlineOutlinedIcon from "@material-ui/icons/WorkOutlineOutlined";
import Input from "@material-ui/core/Input";
import AccountTreeOutlinedIcon from "@material-ui/icons/AccountTreeOutlined";
import { FieldArray, Field, Form, Formik } from "formik";
import { Card, CardContent } from "@material-ui/core";
import Autocomplete from "@material-ui/lab/Autocomplete";
import PostAddIcon from "@material-ui/icons/PostAdd";

const useStyles = makeStyles((theme) => ({
  root: {
    "& > *": {
      margin: theme.spacing(1),
    },
  },
  input: {
    display: "none",
  },
  button: {
    margin: theme.spacing(1),
    // padding: theme.spacing(4),
  },
}));

function ShippingTab(props) {
  const dispatch = useDispatch();
  const classes = useStyles();
  // const [amount, setAmount] = useState("");

  const [jobs, setJobs] = useState([]);
  // const [jobId, setJobId] = useState(0);

  // const [employeeLevel, setEmployeeLevel] = useState("");

  const { enqueueSnackbar, closeSnackbar } = useSnackbar();

  const handleCreateInvoiceMessageClick = () => {
    enqueueSnackbar(
      "Invoice created successfully",
      { variant: "success" },
      {
        anchorOrigin: {
          vertical: "top",
          horizontal: "right",
        },
      },
      { TransitionComponent: Slide }
    );
  };
  const handleAmountChange = (event) => {
    setAmount(event.target.value);
  };

  useEffect(() => {
    getJobs().then((response) => {
      console.log("jobs response in approve: ", response);
      // setJobs(response);
    });
  }, []);

  return (
    <Card>
      <CardContent>
        <Formik
          initialValues={{
            entities: [{ jobId: 0, amount: 0, employeeLevel: " " }],
          }}
          onSubmit={async (values) => {
            console.log("values: ", values);
            return dispatch(addSalaryScale(values));
          }}
        >
          {({ values, isSubmitting }) => (
            <Form autoComplete="off">
              <Grid container>
                <Grid item>
                  <FieldArray name="entities">
                    {({ push, remove, Formik }) => (
                      <React.Fragment>
                        {values?.entities.map((_, index) => (
                          <Grid container item key={index}>
                            <Grid item>
                              <Field
                                name={`entities[${index}].jobId`}
                                id="entities.jobId"
                                component={TextField}
                                label="JobId"
                              />
                            </Grid>

                            <Grid item>
                              <Field
                                name={`entities[${index}].amount`}
                                id="entities.amount"
                                component={TextField}
                                type="number"
                                label="amount"
                              />
                            </Grid>

                            <Grid item>
                              <Field
                                name={`entities[${index}].employeeLevel`}
                                id="entities.employeeLevel"
                                component={TextField}
                                label="employeeLevel"
                              />
                            </Grid>

                            <Grid item>
                              <Button onClick={() => remove(index)}>
                                Delete
                              </Button>
                            </Grid>
                          </Grid>
                        ))}

                        <Grid item>
                          <Button
                            onClick={() =>
                              push({ jobId: 0, amount: 0, employeeLevel: "" })
                            }
                          >
                            Add
                          </Button>
                        </Grid>
                      </React.Fragment>
                    )}
                  </FieldArray>
                </Grid>
              </Grid>

              <pre>{JSON.stringify({ values }, null, 4)}</pre>
              <button type="submit">Submit</button>
            </Form>
          )}
        </Formik>
      </CardContent>
    </Card>
  );
}

export default ShippingTab;

salaryScaleSlice.js:

export const addSalaryScale = createAsyncThunk(
  "salaryScalesApp/salaryScale/addSalaryScale",
  async (salaryScale, { dispatch, getState }) => {
    console.log('salary Scale: ', salaryScale)
    const response = await axios.post("/salary-scales", salaryScale);
    const data = await response.data.data;
    console.log("Hi I am Here in add new Job: ", data);
    dispatch(getSalaryScales());

    return data;
  }
);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

祁梦 2025-02-11 17:34:45

400 means you have an error in your Request (i.e. wrong url-param, missing body, etc.). -> https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400

由于响应表明“实体”是一个无效的字段,所以我猜是API服务器可能需要工作的某些字段(例如'jobid')。但是,如果没有进一步的知识或与宣传文档的链接,这只是一个猜测。

最好的方法是联系承包公司的管理员,并要求他向您发送正确的格式和工作请求,以便您有一些测试数据。
...希望这有帮助

400 means you have an error in your Request (i.e. wrong url-param, missing body, etc.). -> https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400

Since the Response shows you that 'entities' is an invalid field my guess is that some of the fields (like 'jobId') are required for the API-server to work probably. But without further knowledge or a link to the swagger documentation this is just a guess.

Best approach would be to contact the admin of the contracting company and ask him to send you a correctly formatted and working request so that you have some test-data.
...hope this was any helpful

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文