将获取帖子请求转换为axios帖子请求

时间:2020-10-17 11:41:40

标签: api axios fetch

我正在尝试将以下fetch请求转换为axios,但失败了

export const createPost = postData => dispatch => {
  fetch('https://jsonplaceholder.typicode.com/posts', {
    method: 'POST',
    headers: {
      'content-type': 'application/json'
    },
    body: JSON.stringify(postData)
  })
    .then(res => res.json())
    .then(post =>
      dispatch({
        type: NEW_POST,
        payload: post,
      })
    );
};

这就是我的做法

export const createPost = postData => dispatch => {
  axios({
    method: "post",
    url: "https://jsonplaceholder.typicode.com/posts",
    headers: {
      'content-type': 'application/json',
    },
    body: JSON.stringify(postData),
  })
    .then((res) => dispatch({
        type: NEW_POST,
        payload: res,
      }))
    .catch((err) => console.log(err));
}

这是调用上述函数的方式。

const post = {
  title: this.state.title,
  body: this.state.body
};

this.props.createPost(post);

您能帮我吗?

0 个答案:

没有答案