繁体   English   中英

使用Express.js在服务器上发送POST请求

[英]Send a POST request on the server with Express.js

我遇到了一个小问题,认为我有可能做到。

我想要两条快速路线,一条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请求将用户发送到页面。

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

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

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

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))

您可以使用request-promise将数据发布到url。 因此,启动此功能,您可以在api网址中获取数据

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...
        });

抱歉如果我的问题错了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM