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

问题描述 投票:0回答:1

我正在制作一个演示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);
  }

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

node.js reactjs react-redux
1个回答
0
投票

fetch返回原始响应对象。 为了获得预期的数据,您应该在原始响应对象上调用.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使其更具可读性:

export const createPost = (postData) => async (dispatch) => {
  // send postData to server
  const rawResponse = await fetch(`${Config.address}/post`, {
    method: 'POST',
    headers:{
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(postData)
  });

  // we are done with server but we need one more step

  // turn a raw response to readable JS object
  const message = await rawResponse.json()

  // message from server response 
  console.log('Message ', message);

  // store same object as we sent to server in redux store
  dispatch({ type: NEW_POST, payload: postData });
}

希望能帮助到你

© www.soinside.com 2019 - 2024. All rights reserved.