reactjs - AXIOS Post 停留在我的 REACT 应用程序中
问题描述
下面是在创建/更新配置文件的onSubmit时将分派的 Redux Action 代码:
我正在使用AXIOS lib 对后端MongoDB进行以下POST调用。
const res = await axios.post(
'/api/profile',
formData, // Body
config // Headers
);
在我的 React 应用程序中,上述代码行适用于Create但对于Update,它没有返回任何内容,并且在 Chrome Dev Tools 的 Networks 选项卡中,状态为Pending。有人可以帮助我了解我会在哪里犯错吗?
当我使用具有相同标头和有效负载数据的Postman发出POST请求 时,Create/Update 调用都运行良好。
以下是完整代码:
// Create/Update Profile
export const createProfile = (formData, history, edit = false) => async (
dispatch
) => {
try {
const config = {
headers: {
'Content-Type': 'application/json',
},
};
debugger;
const res = await axios.post(
'/api/profile',
formData,
config
);
dispatch({
type: GET_PROFILE,
payload: res.data,
});
dispatch(setAlert(edit ? 'Profile Updated' : 'Profile Created'), 'success');
if (!edit) {
history.push('/dashboard');
}
} catch (error) {
const errors = error.response.data.errors;
if (errors) {
errors.forEach((error) => dispatch(setAlert(error.msg, 'danger')));
}
dispatch({
type: PROFILE_ERROR,
payload: {
msg: error.response.statusText,
status: error.response.status,
},
});
}
};
解决方案
您的数据发送方式有问题。
您正在选择content-type: application/json
标题,而您正在以字符串形式发送数据。
解决方案:
如果您的 formData 变量是 FormData 类的实例,则将您的标题内容类型更改为x-www-form-urlencoded
.
如果您的 formData 是一个简单对象,则不要在 axios.post 方法中使用 JSON.stringify。
同时更新您的 axios 请求:
const res = await axios.post(
'http://localhost:5000/api/profile',
formData,
config
);
我希望它有帮助
推荐阅读
- node.js - 使用 mocha 和 chai 进行单元测试时出现权限不足错误 Node.js
- sql - SQL 减法使用多个 CASE WHEN ELSE 导致 GROUP BY 问题
- reactjs - 如何删除语义 ui 反应的构建步骤?
- node.js - Jest 试图在不应该应用的部分使用 babel
- python - 从json正文中获取元素的确切值
- scheme - 我试图从我从这个方案脚本得到的结果中匹配一个字符串“#\x”,但我总是得到最终输出为 FALSE
- linux - Shell脚本将文件的每一行存储到单独的文件中
- java - StringTokenizer 中不需要的行为
- rust - 从原始库`use super`重构impl
- python - Kivy字体大小问题