redirect post request from post request - node.js

trying to send post form request to another server.
I'm getting post request from my localhost lets say on POST /deposit
and I want later to redirect user to payment website with some kind of this data
​form to which I want user to redirect after he posts to: localhost:3000/deposit
<form action='http://testpayment.com/pay' class='redirect_form' method='post'>
<input type='hidden' name='key' value='${data.api_id}'>
<input type='hidden' name='signature' value='${data.api_secret_key}'>
<input type="hidden" name='user_id' value='${data.user_id}'>
<input type="hidden" name="payment_method" value="master_card">
<input type="hidden" name="customproduct" value='[{
"productId":"deposit-${currencyPayway.currency.code}",
"productName":"Test Product",
"productType":"fixedProduct",
"currency":"${currencyPayway.currency.code}",
"amount":${amount}}]'>
<button type='submit'>Pay</button>
</form>
Post route:​
app.post('/deposit', function(req, res) {
// some logic applies here
//redirect part ???
});
Any ideas how to do it?
Thanks.
UPDATE:
Use case of what I'm ting to do:
Lets say we have multiply payment providers. On deposit action in any way after applying some logic we need to redirect user to payment provider website for card/account details input after which user will be redirect to my website back again by payment provider. Now front writes custom logic for all deposit methods each time. But I tries to decouple front from that stuff and handle it completely on backend and unify deposit process.

In most cases as I know, paymant gateway works like this:
you will create a form and as an URL you put your Payment Provider URL https://secure.paymentprovider.com/deposit
you will create a form get the data from user, send on server side to Payment Provider, as a return you should get a SessionId, some kind of unique key and then you redirect user but with a GET method to Payment Provivder url ie. https://secure.paymentprovider.com/deposit/{token/sessionId}
Here is an example PayU - http://developers.payulatam.com/en/web_checkout/
Maybe you can attach link to Payment Provider api?

use stream.pipe
https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
app.post('/', (req, res,next) => {
var request = require('request');
var pipe = req.pipe(request.post('localhost:3000/deposit'));
var response = [];
pipe.on('data',function(chunk) {
response.push(chunk);
});
pipe.on('end',function() {
var res2 = Buffer.concat(response);
console.log(res2);
res.send(res2)
});
})

Related

How to send data from react.js to node?

I am a beginner in web devolopment and I'm developing an application using react and nodejs. I've been looking for ways to send the data from front end i.e, react(data received from the user) to nodejs code so that I can process it and send it back to the UI. I saw some resources mentioning that I can use fetch and axios but I can't quite follow it. So basically my application is about executing the pipe commands of linux. There will be few buttons to choose which command to execute(Like sort, uniq etc). There will be a text area to get the input text and a label to display the output. So how can I send the input data to the nodejs function so that I can process it with some built-in modules and return the output to the label.My code for text area looks like this
import { useState } from "react";
const Text_area = () =>{
const[text,setText] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
const data = {text};
}
return(
<>
<form onSubmit={handleSubmit}>
<label>Input here</label>
<textarea value= {text} required onChange={(e)=>setText(e.target.value)}/>
<button>OK</button>
</form>
</>
);
}
Share your thoughts please!
I assume you have only index route, that's why fetch is pointing to index.
const[text,setText] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
const newText= { text };
fetch("/", {
method: "POST",
headers: {"Content-Type": "application/JSON"},
body: JSON.stringify(newText)
})
}
Above, fetch method is used to send your data to relevant route in your node.js file.
And in your server.js file, you can code something like this to see if it works:
app.post("/", function(req, res){
res.send(req.body);
});
Please let me know if it works for you.
Think of your problem like a Form HTML element. How can a form send data to server?
Basically, they use HTTP GET/POST method. If you don't know it, Google! But for now, let just understand that: To send data from react.js to node, you need do something with HTTP GET/POST method.
<form action="/send_form" method="post">
<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname">
<input type="submit" value="Submit">
</form>
form element has done it for you. This is why you see people mentioned axios because what if I don't use form? How can I do the same thing without form?
Then how do server receive information? You will do that by code something in Node.js. Googled yourself :>.
Then people mentioned Express.js. Think of it as "React" of Node.js, which mean it's a framework. You don't need to know "Express.js" to receive information sent from React.

NodeJS form submit issues

I am attempting to submit data in my NodeJS app. I've been using Postman with a single name entry in json and my app is able to detect the post body data. Screen shot below:
My problem is I can't get my html markup to submit data successfully. I provide the data to the form but the nodejs function receiving the submission shows that the request data is empty.
The following is the form markup:
<form id="join_queue" action="/join_queue" method="post" enctype="application/json">
<label for="">Please provide a name: </label>
<input type="text" name="name" id="name">
<input type="submit" value="Join">
</form>
And here is my Nodejs function responding to the form submission:
app.post('/join_queue', (req, res) => {
console.debug('Post body: ', req.body)
console.debug('Post param: ', req.params)
res.render('join.ejs')
})
All I get is Post body: {} and the same for params.
What am I doing wrong or missing here? How can I get my html form to behave the same as the postman form?
I needed to include the body-parser middleware in order to get form submission data as indicated here.
I.E:
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }));

"Waiting for localhost" after form submission: node/express/react

I am working with node/express/react. I am using a form on the frontend to delete entries from the backend database:
<form id="delete" action="/delete" method="POST">
<p>First name:</p>
<input type="text" name="first" />
<p>Last Name:</p>
<input type="text" name="last" />
<input type="submit" value="delete person from database" />
</form>
The entry gets deleted from the backend database. But I get this message at the bottom of the browser window on the frontend:
Waiting for localhost...
Then after about a minute, I get this:
"This page isn’t working
localhost didn’t send any data.
ERR_EMPTY_RESPONSE"
Here is the relevant express endpoint:
app.post('/delete', function(req, res) {
var first = req.body.first;
var last = req.body.last;
db.collection("employees").remove({first:first, last:last}, function(error, response) {
if (error) throw error;
console.log("success");
});
});
If I do send data via res.send() or res.json(), then the entire front-end web page gets erased and replaced with whatever data was sent from the backend.
Often with form submission, you send the user to a different web page after submit. But in my case, I want the user to stay on the same page without reloading the page.
How do I get the error messages to go away in this case?
For the node/express part of the question, "How do I get the error messages to go away in this case?", you have to send some sort of response from the endpoint:
app.post('/delete', function(req, res) {
var first = req.body.first;
var last = req.body.last;
db.collection("employees").remove({first:first, last:last}, function(error, response) {
if (error) throw error;
console.log("success");
res.status(200).send({msg: `Deleted ${first} ${last}, RIP`}); //returning a status object, but you could return anything useful to the client code here.
});
});
This gets rid of the error, but you would still be redirected to a page showing the JSON output from the API.
Staying on the same page after submitting a form is discussed here and many other posts as well. You mention it is a React app--you might want to use that framework for making API calls from your frontend.

How to send the JWT token to the client with feathersjs-authentication?

I'm using local authentication in my feathersjs REST-API application, but after the user is authenticated, instead of sending me the authentication token, feathers is sending the following HTML as a response to the authentication request:
<body>
<img class="logo" src="alongbase64string" alt="Feathers Logo">
<main>
<h1 class="center-text">Success</h1>
<h3 class="center-text">You are now logged in. We've stored your JWT in a cookie with the name
<span class="italic">"feathers-jwt"</span> for you. It is:
</h3>
<pre id="token"></pre>
</main>
<script type="text/javascript">
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
var token = getCookie('feathers-jwt');
var el = document.getElementById('token');
el.innerHTML = token;
</script>
which prints the following page:
I think this would work good enough if I was sending the request from a web page, but in my case I need to get the token, because the client is a mobile app, not a web browser, so cookies won't work for me.
Is it possible for me to make feathersjs send the token in the response? Something like:
{
token: 'açldkjfaçldkfjçasdkfjdçakfjd'
}
This way I could store the token in the mobile app, and use it to authenticate further requests to my feathersjs API server.
For now I won't put any more code here, because the application was made entirely with the console commands available by feathersjs, like feathers generate but if anyone needs to understand more about the code, just let me know, and I will edit the question adding more details.
You have to make sure to set the Accept header in your request to application/json otherwise it'll assume HTML and send the page you are seeing.
Use the local middleware instead of the socket scheme referenced in the question.
POST'ing login data to /auth/local will yield
{
"token": {JWT},
"data": {
"email": "admin#feathersjs.com",
"id": 0
}
}
Your client can pull values from that JSON response and handle them appropriately.
Most anything beyond that will require modifying the stock Feathers demo.

backbone model.save() does not set the response body of the express server with body parser

I am trying to save (post) a Backbone model using a model.save().
Model:
Backbone.Model.extend({
urlRoot: '/project/',
defaults: {
projectname: "default projectname"
}
});
Saving the model (in my Backbone.router object):
putTest: function(id) {
var projectItem = new ProjectModel({projectname: "This shiny new project"});
projectItem.save();
},
I would expect my node/express router on the server, which uses the middleware 'body-parser', to get the attributes of the model on the express request.body object, like so:
post: function(request, response) {
console.log(request.body.projectname);
}
but the response.body object is empty.
When I am using a regular html form with method="post" like so:
<form id = "createProject"
action = "/project/"
method = "post" >
<input type="text" name="projectName" value="Project name" />
</form>
everything is working as expected.
I have struggled with this the whole day now, and can't see what I am doing wrong.
Have I misunderstood the whole Backbone.model.save() concept or is there an other object on the express request object that holds the attributes of my Backbone model when saving?
By default, an HTML <form> sends application/x-www-form-urlencoded data and no JSON like Backbone.sync() does (that's used by .save() internally).
Open your browser's developer tools and take a look in the network analysis when saving the model to make sure the request works correctly (JSON Body, URL, ...).
However, since your backend handles form data correctly, I'd guess your middleware is not configured in the way you want it to.

Resources