Send a POST request on the server with Express.js

二次信任 提交于 2021-02-11 07:44:18

问题


I'm running into a small issue with something I thought was possible.

I want to have two express routes, one GET route /post-data and one POST route /post-recieve.

The code would look something like this:

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

Now, when you visit /post-data you should be instantly redirected to /post-recieve except if you look in the developer console you should see that the method for the document is POST and not a normal GET request.

Is this possible?

I know you can use a library like request to make a HTTP post request to an endpoint, but I'm talking about actually sending the user to the page via a POST request.


回答1:


This feels so dumb, but it might be the only way???

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:


The only way to change the client's request method from GET to POST programmatically is to create a form containing hidden elements with method="post" and action="/post-receive", then using client-side JavaScript to automatically submit the form.

Any HTTP redirects in response to a GET request will also be GET.




回答3:


You can use request-promise to post the data to a url. So, initiate with this function and you can get the data in the 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...
        });

Apologies If I get your question wrong.



来源:https://stackoverflow.com/questions/35353480/send-a-post-request-on-the-server-with-express-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!