访问服务器中搜索栏中的值



我想从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从html页面向Node.js服务器上指定的路由发出GET请求。你可以这样做:

function sendSearch() { 
let term = document.getElementById("searchbar").value;
fetch('<your server address>/hotels?search=' + term).then( response => {
//do something with the response
};
}

您可以在窗体的onsubmit事件(如onsubmit='sendSearch()'(或按钮的onclick事件上调用该函数。

在您的server.js中,获取如下查询参数:

app.get('/hotels', function(req, res){
let searchTerm = req.query.search;
...

然后,您可以在GET函数中使用查询参数。

最新更新