react-native - 如何在本机反应中发送 axios 请求?
问题描述
我是 React Native 的新手,我正在尝试将 axios 请求发送到我的后端,但我陷入了困境。
export const login = (email, password) => async dispatch => {
const config = {
headers: {
'Content-Type': 'application/json'
}
};
const body = JSON.stringify({ email, password });
const res = await axios.post(`http://localhost:8000/auth/jwt/create/`, body, config);
console.log('kk');
dispatch({
type: LOGIN_SUCCESS,
payload: res.data
});
dispatch(load_user());
};
虽然我已经在 React JS 中尝试过这个并且它运行良好。请帮助我在本机反应中解决这个问题
解决方案
根据React Native Networking Docs,React Native 支持fetch
Web API来发送请求。我建议您使用fetch
,而不是axios
因为它具有所有相同的功能而没有任何额外的膨胀和开销。这是您要使用的代码的一个端口fetch
:
export const login = (email, password) => async (dispatch) => {
const res = await fetch(`http://localhost:8000/auth/jwt/create/`, {
method: "POST", // this signnifies POST request type
body: JSON.stringify({ email, password }), // still including the body
headers: {
// apply the headers
"Content-Type": "application/json"
}
});
const data = await res.json(); // parses the body as a json object
console.log("kk");
dispatch({
type: LOGIN_SUCCESS,
payload: data
});
dispatch(load_user());
};
推荐阅读
- javascript - 将组件设置插入样式管理器
- ibm-cloud - 工作负载调度程序作业不会启用
- eclipse - 为什么 Eclipse Glassfish 不支持 Eclipse Microprofile
- java - 在 Spark 中读取多行 CSV 文件时,是否有任何选项可以在引号内保留换行符?
- javascript - 将测验中所有单选按钮的标签文本更改为红色和绿色
- javascript - Lodash - 如何从平面数组创建树
- django - 无法连接到 /home/ubuntu/env/Project/Project.sock
- python - Python 算法跳过搜索添加文件夹的新文件
- java - 从 Microsoft Active Directory 中删除未发送的属性
- c# - .NET Dapper/MySql 8.0 问题:只有 root 用户能够执行存储过程。其他用户得到 SqlNullValueException