In: Computer Science
Using Node.js with Express, show how you would create the following routes, using these URL's, as examples:
~ http:#localhost:4200/books/isbn/978123487999/author
This URL will return an author's full name from array of names, mapped by ISBN.
~ http:〃localhost:4200/books
This returns all the books (just the book names) from the database.
If you have any problem with the code feel free to comment.
Program
const express = require('express');
const app = new express();
// http:#localhost:4200/books/isbn/978123487999/author
//sending author name using isbn
app.get('/books/isbn/:isbn/author', (req, res) => {
const isbn = req.params.isbn;
let author;
//searching for author
for (let i = 0; i < authorData.length; i++) {
if (isbn == authorData[i].isbn) {
author = authorData[i].author;
break;
}
}
res.send(author);
});
//return all book names from the database
app.get('/books', (req, res) => {
res.send(booksData);
});
//starting the server
const server = app.listen(4200, () => {
console.log('server has started');
});
//dummy database data for testing
const authorData = [
{
isbn: 978123487999,
author: 'Harper Lee',
},
{
isbn: 124536987456,
author: 'F. Scott Fitzgerald',
},
{
isbn: 523698745156,
author: 'J. D. Salinger',
},
{
isbn: 635124102359,
author: 'Charlotte Brontë',
},
];
const booksData = [
{ name: 'To Kill a Mockingbird' },
{ name: 'The Great Gatsby' },
{ name: 'The Catcher in the Rye' },
{ name: 'Jane Eyre' },
];
Output