我有一个问题,返回数据的“POST”方法到另一个函数,使它得到进一步的进程。我使用Node.js,JavaScript和Express作为后端。
下面是“server.js”中的相关代码:
app.post("/movies", function (req, res) {
const imdbIDs = req.body;
if (!Array.isArray(imdbIDs)) {
res.sendStatus(400);
return;
}
const apiKEY = '########'; // unvisible just for question
const movies = [];
imdbIDs.forEach((imdbID, index) => {
const apiUrl = `http://www.omdbapi.com/?&apikey=${apiKEY}&i=${imdbID}`;
http.get(apiUrl, (response) => {
let responseData = '';
response.on('data', (chunk) => {
responseData += chunk;
});
response.on('end', () => {
try {
const movieData = JSON.parse(responseData);
if (movieData.Response === 'True') {
const movie = {
Released: new Date(movieData.Released).toISOString(),
Runtime: movieData.Runtime !== 'N/A' ? parseInt(movieData.Runtime) : null,
Genres: movieData.Genre.split(',').map(genre => genre.trim()),
Directors: movieData.Director.split(',').map(director => director.trim()),
Writers: movieData.Writer.split(',').map(writer => writer.trim()),
Actors: movieData.Actors.split(',').map(actor => actor.trim()),
MetaScore: movieData.Metascore !== 'N/A' ? parseInt(movieData.Metascore) : null,
imdbRating: Number(movieData.imdbRating)
};
console.log(movie)
movies.push(movie);
} else {
console.error(`Error retrieving movie with imdbID ${imdbID}: ${movieData.Error}`);
}
} catch (error) {
console.error('Error parsing movie data:', error);
}
if (index === imdbIDs.length - 1) {
// Send the movies array as the response
res.status(200).send(movies);
}
});
}).on('error', (error) => {
console.error('Error fetching movie data:', error);
if (index === imdbIDs.length - 1) {
// Send the movies array as the response even if there was an error
res.status(200).send(movies);
}
});
});
});
这里是我想要处理接收数据“index.js”的函数:
function loadMovies(genre) {
const xhr = new XMLHttpRequest();
xhr.onload = function () {
const mainElement = document.querySelector("main");
while (mainElement.childElementCount > 0) {
mainElement.firstChild.remove()
}
if (xhr.status === 200) {
JSON.parse(xhr.responseText)
.forEach(movie => new MovieBuilder(movie, deleteMovie).appendTo(mainElement))
} else {
mainElement.append(`Data could not be loadet, status ${xhr.status} - ${xhr.statusText}`);
}
}
const url = new URL("/movies", location.href)
if (genre) {
url.searchParams.set("genre", genre)
}
xhr.open("GET", url)
xhr.send()
}
我尝试创建一个“constmovies =(xhr.responseData)”,然后调用它,但得到的只是一个“undefined”值。总结一下:在“Server.js”中,我对一个表单发出“POST”请求,所有选中的框都应该存储在一个列表中。该列表应该在“index.js”中调用,其中可以动态构建html。
1条答案
按热度按时间lp0sw83n1#