首页 > 解决方案 > ReactJS:通过 fetch 发布带有数据的请求

问题描述

在我的应用程序组件中,我的状态features包含数组(9)的数组(1500)。我想将状态(或大数组)发送到我的后端,这样我就可以运行我的模型并使用以下函数返回标签:

const getLabels = (model) => {
    fetch('/spotify/get-labels', {headers: {
      'model': model,
      'features': features
    }})
    .then(response => response.json())
    .then(data => setLabels(data))
}

但是,响应的状态为 431。这是意料之中的,但我不确定如何有效地将数据传输到我的后端。也许将其转换为 json 然后放入我的请求的标题中?

标签: reactjs

解决方案


据我了解您的担忧,我想传递'model': model,'features': features身体应该有效。

或者使用 Axios,您可以提出请求。它与 Axios 完全一样,但要好得多

axios({
      url: '/spotify/get-labels',
      method: "post",
      data: {
        'model': model,
      'features': features
      },
    })
      .then((response) => response.json())
      .then(data => setLabels(data))
      .catch((error) => {
        console.log("error : ", JSON.parse(error));
      });


推荐阅读