首页 > 解决方案 > 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,
      },
    });
  }
};

标签: reactjsreact-nativereact-reduxredux-form

解决方案


您的数据发送方式有问题。

您正在选择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
    );

我希望它有帮助


推荐阅读