更新时间:2022-11-07 17:15:53
您的代码没有意义.在第一个路由中,您告诉Express响应302重定向并发送一些数据. 它将向您的客户端发送JSON ,这是您得到正确的Content-Length
的事实.
Your code doesn't make sense. In the first route, you tell Express to respond with a 302 redirect and send some data. It is sending your JSON to the client, something you can see in the fact that you're getting a correct Content-Length
.
但是,您的第二条路线无效.首先,GET
请求不能具有正文; req.body
总是 为空.
However, your second route can't work. Firstly, GET
requests cannot have a body; req.body
will always be empty.
第二,看起来您假设接收到重定向的客户端将向其目标(在这种情况下为 example.com/sending )向其请求中重新提交重定向响应的实体主体. .这是不正确的.
Secondly, it looks like you're assuming a client receiving a redirect will resubmit the entity-body of the redirect response in its request to the target (example.com/sending in this case). This is incorrect.
GET
请求,即使原始请求是POST
.因此,重定向的请求不可能包含任何类型的主体.GET
request, even if the original request was a POST
. Thus, it is impossible for the redirected request to contain any kind of body.如果要将某种数据发送到另一台服务器,则有两个选择:
If you want to send some kind of data to another server, you have two options:
使用303重定向在查询字符串上发送数据.
Send the data on the query string with a 303 redirect.
// I'll use the built-in querystring module to convert an object into
// a properly URL-encoded query string.
res.redirect(303, '/url?' + querystring.stringify(data));
响应200,并使用浏览器端的欺骗手段将数据POST
传送到真实目的地.
Respond 200 and use browser-side trickery to POST
the data to the real destination.
res.send('<form id="redir" method="post" action="/url">' +
'<input type="hidden" name="foo" value="bar">' +
// ...
'</form>' +
'<script>document.getElementById("redir").submit()</script>');
丑陋,但可用于 if ,该功能适用于浏览器.它不适用于服务器或其他非浏览器工具发出的请求.您可能还想为那些坚持在禁用JS的情况下浏览的麻烦对象添加一个继续"提交按钮.
Ugly, but works if this is intended for browsers. It won't work with requests made by servers or other non-browser tools. You might also want to include a "Continue" submit button for the luddites that insist on browsing with JS disabled.
仅当您拥有的数据量将使查询字符串超过URL中实际允许的字符数时才使用此方法(〜
I would only use this method if the amount of data you have will make the query string exceed the amount of characters practically allowable in a URL (~2048) or if the data payload contains sensitive content, which should generally not be included in the query string.