且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Express.js和NodeJS,您能否通过响应正文中的重定向发送JSON

更新时间: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.

  • 符合规范的HTTP客户端绝不会将服务器的响应作为另一个请求的主体发送.
  • HTTP客户端传统上将302视为303,这意味着对目标URL的请求始终是GET请求,即使原始请求是POST.因此,重定向的请求不可能包含任何类型的主体.
  • A spec-compliant HTTP client will never send a server's response as the body of another request.
  • HTTP clients traditionally treat a 302 like a 303, meaning that the request to the target URL is always a 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.