As I understand correctly you want to:
- POST form data to backend
- during data processing, request 3rd party API for a price
- return a price to the user
The form view index.ejs
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<form action="/" method="POST">
<select name="cash" id="first">
<option value="AED">AED</option>
<option value="USD">USD</option>
</select>
<button id="submit" type="submit">Submit</button>
</form>
<% if (cash && price) { %>
<p>The price for <%= cash %> is <%= price %>.</p>
<% } %>
</body>
</html>
I'm using EJS to conditionally display the price below the <form>
.
Here is Express backend:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
// I advise you to use axios instead of request for convenience
const axios = require('axios');
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.get('/', function (req, res) {
if (req.query.cash && req.query.price) {
res.render('index', { cash: req.query.cash, price: req.query.price });
}
res.render('index', { cash: null, price: null });
});
app.post('/', async function (req, res) {
const cash = req.body.cash;
try {
const response = await axios.post(
'paste_your_url', { cash }
);
res.redirect(`/?cash=${cash}&price=${response.data.price}`);
} catch (err) {
console.log(err);
}
});
app.listen(3000);
When the user enters the page /
, Express renders index.ejs
view without price information.
When the user submits the form to backend, Express:
- reads the data,
- requests 3rd party API,
- reads the
price
from 3rd party response,
- redirects user back to
/
with values in query string ?cash=<value>&price=<value>
. This let Express render index.ejs
with price information.
Also, I used axios instead of request, because it makes code more readable and easier (due to async/await
).