如何将 fetch 转换为 axios

Avi*_*ash 6 node.js reactjs

我有以下代码段,运行完美。然而,我的任务是用 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
      }
    })
Run Code Online (Sandbox Code Playgroud)

data 变量是一个包含 req.body 等价物的对象...上面的代码是用 React 编写的,并且在 onSubmit 事件处理程序中调用了 create() 。

我确信如果我使用 axios create() 将被消除..但是如何呢?请指导..

mra*_*lee 6

它不应该与你现在拥有的有太大不同,但类似这样......

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
      }
    })
Run Code Online (Sandbox Code Playgroud)

请注意,您要查找的数据应该位于名为 的属性中data

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