我想从server.js页面的html页面的搜索表单中获取用户输入的值,但不知道如何输入。我知道名称/值对将是cityCode = something,但不知道从那里开始做什么?
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
});
});
最佳答案
由于您的表单使用的是方法GET
,因此您的提交将发送cityCode
作为查询参数。要在Express中访问它,请使用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);
}
});
关于javascript - 从服务器中的搜索栏访问值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61371488/