【问题标题】:Send a POST request on the server with Express.js使用 Express.js 在服务器上发送 POST 请求
【发布时间】:2016-02-12 01:48:43
【问题描述】:

我遇到了一个小问题,我认为这是可能的。

我想要两条快速路线,一条GET路线/post-data和一条POST路线/post-recieve

代码如下所示:

app.get('/post-data', (req, res, next) => { 
  //set url to '/post-recieve' and set body / headers
})  

app.post('/post-recieve', (req, res, next) => {
  return res.json(res.body)
})

现在,当您访问/post-data 时,您应该会立即重定向到/post-recieve,除非您在开发者控制台中查看该文档的方法是POST,而不是普通的GET 请求。

这可能吗?

我知道您可以使用像 request 这样的库向端点发出 HTTP 发布请求,但我说的是通过 POST 请求实际将用户发送到页面。

【问题讨论】:

  • @adeneo 我有一个来自第三方的请求,正在访问我的服务器。我希望能够在我的服务器上模拟该 POST 请求。
  • stackoverflow.com/questions/46582/…en.wikipedia.org/wiki/Post/Redirect/Get。据我了解,客户端只能发出请求方法,例如GET /index.php HTTP/1.1; Host: www.example.org,来自服务器的重定向标头后跟客户端使用相同的方法,例如HTTP/1.1 301 Moved Permanently; Location: http://www.example.org/index.asp。从您的评论中,听起来您想充当代理,在这种情况下,将执行 POST,然后将响应发送给客户端。
  • 有趣的问题,顺便说一句! s.o 上还有很多其他关于更改请求方法的问题,因此您可以在此处进行更多搜索以获取更多信息。

标签: javascript node.js express


【解决方案1】:

这感觉很愚蠢,但这可能是唯一的方法???

function postProxyMiddleware (url, data) {
  return (req, res, next) => {
    let str = []
    str.push(`<form id="theForm" action="${url}" method="POST">`)
    each(data, (value, key) => {
      str.push(`<input type="text" name="${key}" value="${value}">`)
    })
    str.push(`</form>`)
    str.push(`<script>`)
    str.push(`document.getElementById("theForm").submit()`)
    str.push(`</script>`)
    return res.send(str.join(''))
  }
}

app.get('/mock', postProxyMiddleware('/page', exampleHeaders))

【讨论】:

    【解决方案2】:

    以编程方式将客户端的请求方法从 GET 更改为 POST 的唯一方法是使用 method="post"action="/post-receive" 创建一个包含隐藏元素的表单,然后使用客户端 JavaScript 自动提交表单。

    响应 GET 请求的任何 HTTP 重定向也将是 GET。

    【讨论】:

      【解决方案3】:

      您可以使用 request-promise 将数据发布到 url。所以,用这个函数启动,你就可以得到api url中的数据了

      const request = require('request');
      const rp = require('request-promise');
      
      let req = {
              "param1" : "data1",
              "param1" : "data2"       
          }    
          rp({
              method: 'POST',
              uri: 'http://localhost:3000/post-data/',
              body: req,
              json: true // Automatically stringifies the body to JSON
              }).then(function (parsedBody) {
                      console.dir(parsedBody);
                      return parsedBody;
                      // POST succeeded...
                  })
                  .catch(function (err) {
                      console.log(err+'failed to post data.');
                      return err+'failed to post data.';
                      // POST failed...
              });
      

      抱歉,如果我把你的问题弄错了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-12
        • 2019-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多