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

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

问题描述

我正在使用快递 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,用户代理不得自动重定向
请求,除非用户可以确认,否则
会更改发出请求的条件。 p>

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请求重定向在这个伟大的SO答案中解释:

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天全站免登陆