node.js - 如何将 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() 将被消除.. 但是如何?请指导..
解决方案
它不应该与你目前拥有的有太大不同,但是像这样......
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 参考。
推荐阅读
- istio - 如何为多集群 Istio Mesh 设置 PKI
- android - Android - java.lang.NoClassDefFoundError:解析失败:Lorg/slf4j/LoggerFactory;
- java - 如何使mysql中的列保存Java类
- google-sheets - Countifs 订单号 购物篮中有超过 1 件商品
- flutter - flutter_socket_io : 我的事件触发了,我的 JSON 没问题,但是没有发送消息
- javascript - 当我单击此产品时,它不执行任何操作
- python - 将日期时间类型存储在 csv 文件中
- excel - 在 VBA 中定义 LastRow
- laravel - Vue v-bind 事件上的类
- node.js - 检查 node.js 中的文件系统是否区分大小写