为什么 POST 重定向到 GET 而 PUT 重定向到 PUT? [英] Why POST redirects to GET and PUT redirects to PUT?

查看:62
本文介绍了为什么 POST 重定向到 GET 而 PUT 重定向到 PUT?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 express 4.13.3(最新)和以下代码:

I am using express 4.13.3 (latest) and following code:

var express = require('express')

var app = express()

app.get('/test', function (req, res, next) {
  res.send('hello!')
})

app.post('/test', function (req, res, next) {
  res.redirect('/test')
})

app.put('/test', function (req, res, next) {
  res.redirect('/test')
})

app.listen(5001)

// GET /test -> 'hello!'
// POST /test -> 'hello!'
// PUT /test -> ERR_TOO_MANY_REDIRECTS

POST 重定向到 GET,但 PUT 重定向到 PUT.是否可以将 PUT 重定向到 GET(与 POST 相同)?

POST redirects to GET but PUT redirects to PUT. Is it possible to make PUT redirect to GET (same as POST)?

推荐答案

在深入细节之前,以下是您解决问题的一种方法:

Before diving in the details, below is one way of how you could solve the problem:

app.put('/test', function(req, res, next) {
    res.redirect(303, '/test') // Notice the 303 parameter
})

默认情况下,Express 使用 HTTP 代码 302 进行重定向.根据 HTTP 规范,这可以防止 POST/PUT 请求被重定向作为 POST/PUT 请求并解释您在代码中观察到的内容:

By default Express uses HTTP code 302 for the redirect. According to the HTTP specification, this prevents POST/PUT requests from being redirected as POST/PUT requests and explains what you observed in your code:

如果收到 302 状态代码以响应请求,而不是GET 或 HEAD,用户代理不得自动重定向请求,除非它可以被用户确认,因为这可能更改发出请求的条件.

If the 302 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

另一方面,如果您使用 303 重定向,则允许将 POST/PUT 请求重定向为 POST/PUT 请求,如 这个很好的答案:

On the other hand, if you use a 303 redirect, the POST/PUT request is allowed to be redirected as a POST/PUT request as explained in this great SO answer:

303:由于未定义的原因重定向.通常,'操作有完成,在别处继续.客户提出后续请求此资源不应使用新的 URI.客户应遵循POST/PUT/DELETE 请求重定向.

303: Redirect for undefined reason. Typically, 'Operation has completed, continue elsewhere.' Clients making subsequent requests for this resource should not use the new URI. Clients should follow the redirect for POST/PUT/DELETE requests.

这篇关于为什么 POST 重定向到 GET 而 PUT 重定向到 PUT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆