【问题标题】:API Response and Error Message for Invalid Input Data Javascript无效输入数据 Javascript 的 API 响应和错误消息
【发布时间】:2020-07-30 14:08:26
【问题描述】:

假设我有一个存储在我的数据库中的数据列表。那么当用户输入了无效的semesterId 或无效的classId 或无效的dayofWeek 时,如何显示错误信息和API 响应以使我的后端不会崩溃?

以下是发出的请求,其中包含无效的 termId 和错误的 dayofWeek

//SEND REQUEST 
GET http://localhost:3000/basic/result?semesterId=2020100001&classId=4110000001&dayofWeek=9 HTTP/1.1
Content-Type: application/json

这是我的 API

app.get('/basic/result', function (req, res, next) {

  const { classId, semesterId, dayofWeek } = req.query;
  //send the function to the backend 
  database.getDayLecture(classId, semesterId, dayofWeek, (error, result) => {
    const sortResult = backend.minHalls(result);
    if (error) {
      return next(error);
    }else {
        return res.json({
          result: sortResult,
        });
      }
  });
});

谁能帮我解决这个问题?谢谢!

【问题讨论】:

    标签: javascript api httprequest


    【解决方案1】:

    如果我没看错,你应该添加额外的查询参数检查。

    app.get('/basic/result', function (req, res, next) {
    
      const queryParamsValidator = (classId, semesterId, dayofWeek) => {
        return true; // TODO: add your validation logic here
      }
    
      const { classId, semesterId, dayofWeek } = req.query;
    
      if (!queryParamsValidator(classId, semesterId, dayofWeek)) {
        return next('Params are invalid!'); // TODO: specify your error here
      }
    
      database.getDayLecture(classId, semesterId, dayofWeek, (error, result) => {
        const sortResult = backend.minHalls(result);
    
        if (error) {
          return next(error);
        } else {
          return res.json({
             result: sortResult
          });
        }
      });
    
    });
    

    【讨论】:

    • 我可以知道如何在验证逻辑下指定无效数据吗?是classId==null
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-23
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多