如何在react-redux框架上显示来自节点服务器的成功响应

时间:2018-06-27 09:20:07

标签: node.js reactjs react-redux

我正在制作一个演示react-redux应用程序,以基本了解redux,其服务器是在nodeJS上制作的。我做了一个简单的表单,该表单已提交,服务器响应为res.send('FORM SAVED')。在前端,我发出了发布请求,但看不到返回的响应,无论是成功响应。

我的服务器控制器在保存表单详细信息时作出响应。

export const postData = (req, res) => {
    let p = new PostData();
    p.name = req.body.name;
    p.emp_id = req.body.emp_id;
    p.age = req.body.age;
    p.dept = req.body.dept;
    p.phone = req.body.phone;
    p.gender = req.body.gender;
    p.save(((err) => {
      if (err){res.send(`Error in uploading: ${err}`);}
      else {res.send('Form saved');}
    }));
}

这是我的动作:-

 export const createPost = postData => dispatch => {

  fetch(`${Config.address}/post`, {
    method: 'POST',
    headers:{
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(postData)
  })
  .then((post) => {
    console.log('post:', post);
    dispatch({
    type: NEW_POST,
    payload: post
  })
  })
}

这是我在单击提交后在组件中称呼它的方式:-

onSubmit = (e) => {
    e.preventDefault();

      let postData = {
        name: this.state.name,
        emp_id: this.state.emp_id,
        dept: this.state.dept,
        gender: this.state.gender,
        age: this.state.age,
        phone: this.state.phone
      }

      this.props.createPost(postData);
  }

我想获取响应字符串(“表单已保存”),但我不知道如何读取。有人可以帮忙吗?预先感谢

1 个答案:

答案 0 :(得分:0)

fetch返回 raw 响应对象。为了获得预期的数据,您应该在{em {raw}}返回的{em> raw 响应对象上调用.json()方法,如下所示:

fetch

使用export const createPost = postData => dispatch => { fetch(`${Config.address}/post`, { method: 'POST', headers:{ 'Content-Type': 'application/json' }, body: JSON.stringify(postData) }) .then(response => response.json()) // add this line .then((post) => { console.log('post:', post); // you should get an object with `Form saved` or something similar to it dispatch({ type: NEW_POST, payload: postData // replace it to the input parameter }) }) } 更具可读性:

async/await

希望有帮助