Reputation:
I would like to get the value entered by a user from my search form in the html page from my server.js page and can't figure out how. I know that the name/value pair will be cityCode=something but don't know what to do from there?
HTML:
<form class="form-inline my-2 my-lg-0" id="form" action="/hotels" method="GET">
<!-- location search bar -->
<input
class="form-control mr-sm-2"
type="text"
placeholder="Search Location"
aria-label="Search"
id="searchbar"
name="cityCode"
>
<!-- end of location search bar-->
<!-- start of location search button -->
<button class="btn btn-outline-success my-2 my-sm-0" type="submit" id="searchbutton">
Search
</button>
<!-- end of location search button-->
</form>
server.js:
var express = require('express');
var app = express();
app.use(express.static('public'));
var Amadeus = require('amadeus');
app.set('view engine', 'ejs');
app.listen(8080);
app.get('/hotels', function(req, res){
amadeus.shopping.hotelOffers.get({
//'PAR' to be replaced by user input
cityCode: 'PAR'
}).then(function(response){
var jsonData = JSON.parse(response.body);
res.render('pages/onestar', {jsonData: JSON.stringify(jsonData.data[1].type)});
}).catch(function(error){
console.log(error.response); //=> The response object with (un)parsed data
//console.log(error.response.request); //=> The details of the request made
console.log(error.code); //=> A unique error code to identify the type of error
});
});
Upvotes: 0
Views: 52
Reputation: 78890
Because your form is using method GET
, your submit will send cityCode
as a query parameter. To access that in Express, use req.query
:
app.get('/hotels', async function(req, res, next) {
try {
const response = await amadeus.shopping.hotelOffers.get({
cityCode: req.query.cityCode
});
const jsonData = JSON.parse(response.body);
res.render('pages/onestar', {jsonData: JSON.stringify(jsonData.data[1].type)});
} catch (error) {
console.log(error.response); //=> The response object with (un)parsed data
//console.log(error.response.request); //=> The details of the request made
console.log(error.code); //=> A unique error code to identify the type of error
next(error);
}
});
Upvotes: 1
Reputation: 21
You will need to make a GET
request from your html page using JavaScript to the assigned route on your Node.js server. You can do something like this:
function sendSearch() {
let term = document.getElementById("searchbar").value;
fetch('<your server address>/hotels?search=' + term).then( response => {
//do something with the response
};
}
You can call that function on the onsubmit
event of your form, like onsubmit='sendSearch()'
, or on the onclick
event of the button.
And in your server.js, get the query params like this:
app.get('/hotels', function(req, res){
let searchTerm = req.query.search;
...
Then you can use the query params inside your GET
function.
Upvotes: 0