【问题标题】:req.body.jobId shows undefined when passing JobID from a React&Redux frontend to a NodeJS backend?将 JobID 从 React&Redux 前端传递到 NodeJS 后端时,req.body.jobId 显示未定义?
【发布时间】:2020-01-05 07:23:17
【问题描述】:

好的,这会有点长。我对 React 和 Redux 有点陌生。 所以我有一个 React 和 Redux 前端,一个 Node 和 Express 后端以及用于数据库的 mySQL。

我正在构建一个门户网站的一部分,用户可以在其中创建工作。工作创建部分工作正常,但我在从 DB(GET 请求)检索数据时遇到问题。

结构如下:

有一个 postJobs.js 父级,它有几个子组件:

  1. 创建工作
  2. 添加更多详细信息
  3. 分配预算

所有这些子组件都是通过点击标签触发的标签。

当通过 CreateJob 组件创建作业时,会在 DB(主键)中生成一个 jobID,然后将其发送到 Redux Store。

我使用相同的组件,即 CreateJob 用于添加作业和更新作业以防止重复。

当用户成功创建工作时,他/她将导航到第二个选项卡(AddMoreDetails)。

我已经定义了一个用于从数据库中获取创建的作业的操作,并且该操作将 jobID 作为参数(jobID 从 Redux 存储中检索并传递给操作)。

但我在 Node 后端得到“job_id is undefined”。我已经意识到它没有从 req.body 获取 jobId,但我无法找出如何将 jobID 从前端发送到后端的替代方法。

我已经在 Postman 中测试过 API,它工作正常。

这是我遇到的错误以及相关的后端和前端代码:

错误

Unhandled rejection TypeError: Cannot read property 'job_id' of 
undefined at jobsDao.getCurrentJob.then.result

后端

userRouter.js

router.get('/getCreatedJob', postJobController.getCreatedJob);

postJob.js

  let getCreatedJob = (req, res) => {
  let jobId = req.body.jobId;
  let skills = [];
  jobsDao.getCurrentJobSkills(jobId).then(result => {
    result.forEach(skill => {
    skills.push(skill.skill_id);
  });
});
  jobsDao.getCurrentJob(jobId).then(result => {
    console.log(result);
    res.send({
      success: true,
      message: 'Got recent Created Job ',
      jobId: result[0].job_id,
      jobTitle: result[0].job_title,
      jobType: result[0].job_type_id,
      jobSkills: skills
     });
   });
 };

jobsDao.js

   let getCurrentJobSkills = jobId => {
     return Promise.using(getDBConnection(), connection => {
       return connection.query(
         `select skill_id from job_skill where job_id = 
          ${connection.escape(jobId)}`
      );
    });
   };

  let getCurrentJob = jobId => {
    return Promise.using(getDBConnection(), connection => {
      return connection.query(
        `select job_id,job_title,job_type_id from job where job_id 
         = ${connection.escape(jobId)}`
     );
   });
  };

前端

apiConfig.js

export default {
   getCreatedJob: {
   url: '/api/secured/client/getCreatedJob',
   method: 'GET',
   data: {
     jobId: ''
   },
   showResultMessage: false,
   showErrorMessage: true
   }
   // Other API calls here
}

postJobAction.js

export const actionGetCreatedJob = data => {
  const request = apiService('getCreatedJob', data);
  return {
    type: GET_CREATED_JOB,
    payload: request
  };
};

reducerPostJob.js

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case GET_CREATED_JOB:
      console.log(action.payload.data);
      return { ...state };
    // Other cases here
    default:
    return state;
  }

}

createJob.js

componentDidMount() {
  const jobId = this.props.clientPostJob.jobId;
  console.log(jobId); // The createdJob is is being logged here 
                         correctly
  if (jobId) {
    this.props.actionGetCreatedJob({jobId})
    .then(() => {
      this.props.actionLoaderHide()
      /* Add logic here for populating the form fields with the 
        data retrieved from db */
    })
      .catch(err => console.log(err));
  }
}

const mapStateToProps = state => {
  return {
  clientPostJob: state.clientPostJob,
  userInfo: state.userInfo.userData,
  jobId: state.clientPostJob.jobId
 };
};

const mapDispatchToProps = dispatch => {
 return bindActionCreators({
     actionLoaderHide,
     actionLoaderShow,
     actionGetCreatedJob,
  },
  dispatch
  );
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(CreateJob);

将 jobID 发送到后端的最佳方法是什么?

【问题讨论】:

  • 如果您创建作业,我认为您不应该使用GET,也许您应该更改您的实现以使用POST 来创建/更新作业。您使用什么库来发送 HTTP 请求?
  • 我使用 POST 创建作业并使用 PUT 更新作业。我正在使用 GET 来获取我创建的作业。我正在使用 axios 处理 HTTP 请求。

标签: mysql node.js reactjs express redux


【解决方案1】:

我个人会使用jobId 作为路径中的参数(/api/secured/client/getCreatedJob/<jobId>)。您的代码表明您正在尝试将其发送到正文中。

1) Send body in method GET axios

2) HTTP GET with request body

【讨论】:

  • 嘿,这似乎有点工作。如果我 console.log(action.payload.data),那么我得到了 jobID,但现在它会抛出 404 错误并显示“找不到端点”。请帮忙。
  • 您是否将您的端点网址定义为...getCreatedJob/:jobId
  • 它正在工作。我必须将请求从 GET 转换为 POST 才能正常工作。感谢您的帮助!
  • 完成。谢谢你的帮助!将其更改为 req.params.id 也有效,同时将方法保持为 GET。
猜你喜欢
  • 2020-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-12
  • 2020-12-18
  • 1970-01-01
  • 1970-01-01
  • 2012-11-12
相关资源
最近更新 更多