【发布时间】:2020-10-28 23:59:13
【问题描述】:
我正在通过 ExpressJS 函数 app.all 呈现页面 http://localhost:3000/book_results/。
当我单击带有操作 POST 的 HTML 表单到名为 book_profile/ 的新路由时,而不是连接到应打开页面 http://localhost:3000/book_profile/[search term] 的 app.post('/book_profile/encoded:id'),而是加载页面 http://localhost:3000/book_results/book_profile/ .
我的代码将新路由附加到旧路由的 URL /book_results。
app.all('/book_results/:encoded_id', function(req, response, err) {
var title_results = req.params.encoded_id;
if (err) {
console.log(err);
}
request("https://www.googleapis.com/books/v1/volumes?q=" + title_results + "&maxResults=40&printType=books",
function(error, resp, data) {
if (!error) {
var gb_data2 = JSON.parse(data);
for (var i = 0; i < 40; i++) {
tempArray.push(gb_data2.items[i]);
count++;
}
var bookArray = [];
var bookList = [];
if (err) {
console.log(err);
}
const perPage = 10;
let currentPage = 1;
const totalBookList = tempArray.length;
const pageCount = Math.ceil(totalBookList / perPage);
if (req.query.page) {
currentPage = parseInt(req.query.page, 10);
}
while (tempArray.length > 0) {
bookArray.push(tempArray.splice(0, perPage))
}
bookList = bookArray[+currentPage - 1];
const start = (currentPage - 1) * perPage;
const end = currentPage * perPage;
response.render('book_results', {
books: bookList,
bookSearchTerm: title_results,
pageCount: pageCount,
currentPage: currentPage
});
}
});
});
这是http://localhost:3000/book_results/[search term]页面上的表单代码
<div id="seeResults">
<h1>search results for " <%= bookSearchTerm%> "</h1>
<% if(books){%>
<%books.forEach(function(b) { %> <form id="results" method="post" action="book_profile/<%=b.title%>">
<input id="book-image_search" type="image" src=<%=b.volumeInfo.imageLinks.thumbnail === undefined
? " "
: b.volumeInfo.imageLinks.thumbnail %>>
</form>
<%}); %>
<%} %>
</div>
这是表单操作帖子应连接到的app.post('/book_results') 的代码。
app.post('/book_profile/:encoded_id', function(req, response, err) {
var title = req.params.encoded_id;
if (err) {
console.log(err);
}
request("https://www.googleapis.com/books/v1/volumes?q=" + title,
function(error, resp, data) {
if (error) {
console.log(error);
} else {
var gb_data = JSON.parse(data);
const gb_description = gb_data.items[0].volumeInfo.description;
const gb_image = gb_data.items[0].volumeInfo.imageLinks.thumbnail;
const gb_title = gb_data.items[0].volumeInfo.title;
const gb_author = gb_data.items[0].volumeInfo.authors;
const gb_isbn13 = gb_data.items[0].volumeInfo.industryIdentifiers[0].identifier;
const gb_isbn10 = gb_data.items[0].volumeInfo.industryIdentifiers[1].identifier;
const gb_pageCount = gb_data.items[0].volumeInfo.pageCount;
const gb_printType = gb_data.items[0].volumeInfo.printType;
response.render('book_profile', {
book_description: gb_description,
book_image: gb_image,
book_title: gb_title,
book_author: gb_author,
book_isbnTen: gb_isbn10,
book_isbnThirteen: gb_isbn13,
book_pageCount: gb_pageCount,
book_printType: gb_printType
});
}
});
});
【问题讨论】:
标签: javascript html node.js forms express