next.js Axios错误:当使用Axios在React中发送POST请求时,请求失败,状态代码为400

cgyqldqp  于 2023-11-18  发布在  iOS
关注(0)|答案(1)|浏览(197)

我正在构建一个React应用程序,并尝试使用Axios向我的Strapi后端API发送POST请求。但是,我遇到了以下错误:

{
  "message": "Request failed with status code 400",
  "name": "AxiosError",
  "stack": "...",
  "config": {
    "transitional": { ... },
    "adapter": [ ... ],
    "transformRequest": [ ... ],
    "transformResponse": [ ... ],
    "timeout": 0,
    "xsrfCookieName": "XSRF-TOKEN",
    "xsrfHeaderName": "X-XSRF-TOKEN",
    "maxContentLength": -1,
    "maxBodyLength": -1,
    "env": { ... },
    "headers": { ... },
    "method": "post",
    "url": "http://localhost:1337/api/products",
    "data": { ... }
  },
  "code": "ERR_BAD_REQUEST",
  "status": 400
}

字符串
以下是我的React代码的相关部分:

const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [image, setImage] = useState("");
const [price, setPrice] = useState("");
const [brand, setBrand] = useState("");

const handleSubmit = async (e) => {
  e.preventDefault();

  axios
    .post(process.env.NEXT_PUBLIC_API_URL + "/products", {
      "data": {
        "name": name,
        "description": description,
        "image": image,
        "price": price,
        "brand": brand
      },
    })
    .then((response) => {
      console.log(response);
    })
    .catch((error) => {
      setError(error);
      console.log(error);
    });
};


我已经检查了API URL,它似乎是正确的。请求负载似乎也是有效的JSON。但是,我仍然得到一个400 Bad Request错误。有人能帮助我了解可能导致此问题的原因以及如何解决它吗?
编辑:我做了更多的研究,它看起来像我得到的错误,当我试图张贴一个图像的网址。我试图离开图像空,我得到了200。

{
"data": null,
"error": {
    "status": 400,
    "name": "ValidationError",
    "message": "1 relation(s) of type plugin::upload.file associated with this entity do not exist",
    "details": {
        "errors": [
            {
                "path": [],
                "message": "1 relation(s) of type plugin::upload.file associated with this entity do not exist",
                "name": "ValidationError"
            }
        ]
    }
}


}

ojsjcaue

ojsjcaue1#

最后想出了解决方案。对于下面感兴趣的人:

**1.将图片上传到Strapi后端:**首先,您需要将图片上传到Strapi后端。这是通过图片的URL完成的。本质上,您告诉Strapi图片在互联网上的位置,以便它可以检索和存储它。
**2.将图片连接到产品:**上传图片后,下一步是将其与Strapi数据库中的特定产品相关联。这意味着当有人在您的应用程序或网站中查看产品时,他们也会看到您上传的图片。您可以在创建产品的同一表单中执行此关联。这就像在产品列表中添加图片,以使其对用户更具吸引力和信息量。
**3.集成流程:**这里的关键点是,图片上传和链接到产品都是通过同一个表单进行的。这种集成简化了流程,允许您一次性处理创建产品和将图片附加到产品的两项任务。

代码如下:

const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [imageURL, setImageURL] = useState("");
  const [price, setPrice] = useState("");

  const uploadImage = async (imageUrl) => {
    try {
      const imageResponse = await fetch(imageUrl);
      const imageBlob = await imageResponse.blob();

      const formData = new FormData();
      formData.append('files', imageBlob, imageUrl);

      const uploadResponse = await axios.post(`${process.env.NEXT_PUBLIC_API_URL}/upload`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });
      return uploadResponse.data[0].id;
    } catch (error) {
      setError(error);
      console.error("Error uploading image:", error);
      return null;
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    const uploadedImageId = await uploadImage(imageURL);
    
    if (uploadedImageId) 
    {
      axios.post(`${process.env.NEXT_PUBLIC_API_URL}/products`, {
        data: {
          name: name,
          description: description,
          image: uploadedImageId,
          price: price,
        },
      })
      .then(response => {
        console.log('Product created:', response);
      })
      .catch(error => {
        setError(error);
        console.error('Error creating product:', error);
      });
    }
  };

个字符

相关问题