ThomasReggi
ThomasReggi

Reputation: 59345

Send a POST request on the server with Express.js

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.

Upvotes: 1

Views: 1425

Answers (3)

chandoo
chandoo

Reputation: 1316

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.

Upvotes: 0

ThomasReggi
ThomasReggi

Reputation: 59345

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

Upvotes: 1

Dr. McKay
Dr. McKay

Reputation: 2977

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.

Upvotes: 0

Related Questions