【问题标题】:React Axios - Pass Hook as Parameter for Axios ParamsReact Axios - 传递 Hook 作为 Axios 参数的参数
【发布时间】:2022-11-20 23:51:40
【问题描述】:

我是 React 和 Axios 的新手,我正在努力研究如何根据用户输入更改 GET 实例属性......如果我以错误的方式进行操作,请指导我。

我希望将选定的数据格式传递给 Axios.getData() 的参数

目前我只能让它传递对象而不是它的值。

提前致谢

下面是获取数据的代码:

function App() {
  let [responseData, setResponseData] = React.useState([]);
  const [dataFormat, setDataFormat] = React.useState("json");

  const fetchData = (e) => {
    e.preventDefault();
    console.log({dataFormat});
    api
      .getData(dataFormat)
      .then((response) => {
        console.log("Hello");
        console.log(response);
        setResponseData(response.data);
      })
      .catch((error) => {
        console.log(error);
      });
  };

这是 Axios 实例

enter image description here

这是我收到的错误:

enter image description here

【问题讨论】:

  • 来自服务器 localhost:8000,read more 的响应中缺少 Access-Control-Allow-Origin 标头
  • @HarshVishwakarma 它是在 API 的 get 函数中设置的,所以当我对数据类型值进行硬编码时,它不会返回此错误

标签: reactjs react-hooks axios


【解决方案1】:

首先你需要安装 express 库。然后,导入 cors 并使用 express.json() 解析 json,如下所示:

const express = require("express");
const app = express();
const cors = require("cors");

app.use(express.json());

app.use(cors());

function App() {
  let [responseData, setResponseData] = React.useState([]);
  const [dataFormat, setDataFormat] = React.useState("json");

  const fetchData = (e) => {
    e.preventDefault();
    console.log({dataFormat});
    api
      .getData(dataFormat)
      .then((response) => {
        console.log("Hello");
        console.log(response);
        setResponseData(response.data);
      })
      .catch((error) => {
        console.log(error);
      });
  };

【讨论】:

    猜你喜欢
    • 2019-06-18
    • 1970-01-01
    • 2017-07-02
    • 1970-01-01
    • 2020-12-04
    • 2018-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多