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 l
Solution 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))
Solution 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.
Solution 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.
Post a Comment for "Send A Post Request On The Server With Express.js"