简体   繁体   English

Express 服务器错误 400 未返回 json 消息

[英]Express server Error 400 is not returning json message

I am submitting a form and if the form id already exists in the database, I am returning status 400 with a message saying that the form exists.我正在提交一个表单,如果该表单 ID 已存在于数据库中,我将返回状态 400 并显示该表单存在的消息。

res.status(400).send({
   status: 400,
   message: "Form exists"
})

When I read the response sent back from my express server, I am getting Bad request message instead of the custom message object that I am returning.当我阅读从我的快递服务器发回的响应时,我收到了Bad request消息,而不是我返回的自定义消息 object。 If I replace res.status(400) with res.status(200) , I am getting the expected custom message object.如果我将res.status(400)替换为res.status(200) ,我将收到预期的自定义消息 object。

Weird enough, I can get the custom message object when making the server call in development environment.很奇怪,在开发环境中进行服务器调用时,我可以得到自定义消息 object。 I get Bad Request message from my production server and I don't know why the response is different when the environment is different.我从生产服务器收到Bad Request消息,但我不知道为什么当环境不同时响应不同。 I am hosting this server on IIS Manager v10我在 IIS Manager v10 上托管此服务器

So my question is should I use status code of 200 instead of 400 in this scenario?所以我的问题是在这种情况下我应该使用 200 而不是 400 的状态码吗? Is there a way to return a custom message from status 400?有没有办法从状态 400 返回自定义消息? Based on my understanding, I should use 4xx status code if there is a client input errors eg there is already an existing ID or invalid inputs.根据我的理解,如果有客户端输入错误,例如已经存在 ID 或无效输入,我应该使用 4xx 状态码。

Edit: This is my code from my React app.编辑:这是我的 React 应用程序中的代码。

axiosInstance
        .post("/form/some-endpoint", formData)
        .then(function () {
          navigate(ROUTE_SUCCESS_PAGE);
        })
        .catch(function (error) {
          // eslint-disable-next-line no-console
          console.log(error);
          alert(error.response !== undefined ? error.response.data.message : error.message);
        });

This is the actual screenshot of the response from prod server (I console log it)这是来自 prod 服务器的响应的实际屏幕截图(我控制台记录它)

在此处输入图像描述

在此处输入图像描述

But in development environment, I am getting the response that I wanted.但是在开发环境中,我得到了我想要的响应。 在此处输入图像描述

在此处输入图像描述

Postman response from Prod server:来自 Prod 服务器的 Postman 响应: 在此处输入图像描述

should I use status code of 200 instead of 400 in this scenario在这种情况下我应该使用状态码 200 而不是 400

TLDR: It depends on the usage. TLDR:这取决于使用情况。

If your intent is to U pdate a form, like using a PUT request, you should require an id and if that id does not exist, return 404 .如果您的意图是PUT请求,您应该需要一个id ,如果该id不存在,则返回404

If you are looking to C reate new form, like using a POST request, with an id or other meta data and one already exists matching the id or meta data (eg groupId ), then 400 is fine but it could be better to use 409 stating that there is a conflict with the existing state, that being a preexisting form id or meta data.如果您正在寻找C创建新表单,例如使用POST请求,带有id或其他元数据,并且已经存在匹配id或元数据(例如groupId ),那么400很好,但使用409可能会更好说明与现有的 state 存在冲突,这是一个预先存在的表单 ID 或元数据。 Though you don't often pass an id to a POST create request.尽管您不经常将id传递给POST创建请求。

The full list of codes is a great place to start, but sometimes it helps to see how certain codes are used in production APIs.完整的代码列表是一个很好的起点,但有时它有助于了解某些代码在生产 API 中的使用方式。 A good place to look is the GitHub API which shows the possible status codes for each endpoint along with a description.一个不错的地方是GitHub API ,它显示了每个端点的可能状态代码以及描述。 Take the Pulls API for example, just searching for 40 on the page gives you a lot of insight about when certain codes are used.Pulls API为例,只需在页面上搜索40 ,您就可以深入了解何时使用某些代码。

Comparing these statuses with your example, if you look at the PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge route, they use 409 whenever Conflict if sha was provided and pull request head did not match .将这些状态与您的示例进行比较,如果您查看PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge路线,只要Conflict if sha was provided and pull request head did not match ,它们就会使用409 This seems similar in nature to the POST request described above.这在本质上似乎与上述POST请求相似。

At the end of the day the crucial part is to get in the correct grouping (ie 2xx , 4xx , etc.) after that it's more about being consistent across your API than matching the codes to exact best option.归根结底,关键部分是进入正确的分组(即2xx4xx等),之后更重要的是要在 API 中保持一致,而不是将代码匹配到确切的最佳选项。 Also everyone is different and some may choose different codes for the same use case.而且每个人都是不同的,有些人可能会为同一个用例选择不同的代码。


As far as changing the response itself on 400 status, you should be able to achieve this by setting statusMessage directly and then call res.end .至于在400状态上更改响应本身,您应该可以通过直接设置statusMessage然后调用res.end来实现这一点。

function(req, res) {
  res.statusMessage = "Form exists";
  res.status(400).end();
}

Also see https://stackoverflow.com/a/36507614/6943587另请参阅https://stackoverflow.com/a/36507614/6943587

<system.webServer>
    <httpErrors existingResponse="PassThrough" />
</system.webServer>

Adding the <httpErrors existingResponse="PassThrough" /> to the server's web.config file on IIS Manager resolved my issue.在 IIS 管理器上将<httpErrors existingResponse="PassThrough" />添加到服务器的 web.config 文件中解决了我的问题。 Based on my understanding, bypassing the http error handler and not letting IIS to send its response is the solution that I need.根据我的理解,绕过 http 错误处理程序并且不让 IIS 发送其响应是我需要的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM