首页 > 解决方案 > 如何将 fetch 转换为 axios

问题描述

我有以下一段完美运行的代码。但是,我的任务是用 axios 替换 fetch。你能指导一下,axios中代码的正确替换是什么?

const create = async (credentials, software) => {
  return await fetch('/api/software/create', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + credentials.t
    },
    credentials: 'include',
    body: JSON.stringify(software)
  })
    .then((response) => {
      return response.json()
    }).catch((err) => console.log(err))
}

create({ t: jwt.token }, data)
    .then((data) => {
      if (data.error) {
        this.setState({ error: data.error })
      } else {
        this.props.dispatch(initSoftware()); //if successful get the list of softwares in redux store
      }
    })

data 变量是一个持有 req.body 等价物的对象......上面的代码是用 react 编写的,create() 在 onSubmit 事件处理程序中被调用。

我敢肯定,如果我使用 axios,create() 将被消除.. 但是如何?请指导..

标签: node.jsreactjs

解决方案


它不应该与你目前拥有的有太大不同,但是像这样......

const create = async (credentials, software) => {
  return await axios({
    url: '/api/software/create'
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + credentials.t
    },
    withCredentials: true,
    data: JSON.stringify(software)
  })
    .then((response) => {
      return response.data;
    }).catch((err) => console.log(err))
}

create({ t: jwt.token }, data)
    .then((data) => {
      if (data.error) {
        this.setState({ error: data.error })
      } else {
        this.props.dispatch(initSoftware()); //if successful get the list of softwares in redux store
      }
    })

请注意,您要查找的数据应位于名为data.

有关更多信息,请在此处查看 API 参考。


推荐阅读