I am trying to make a simple website that utilizes the google books API so users can search for books. I am starting the server using express in index.js in the root directory of the project and have my static files in a directory called public. In my index.html I have a form to collect user input and am not understanding how to use that input as a query parameter for my GET request in my index.js file. I am trying to create the GET request in the index.js file so that I can call it in my script.js file and parse the data there. I have the pieces but I don't know how to connect them all together.
form from index.html
<form id="submit">
<label for="query">Enter Book Query</label><br>
<input type="text" id="query" placeholder="Search For Books!">
<input type="submit" value="Submit">
</form>
from script.js
var submit = document.getElementById('submit')
submit.addEventListener('submit', function(event){
event.preventDefault()
query = document.getElementById('query').value
})
from index.js
const express = require('express')
const app = express()
const port = 3000
app.use(express.static('public'))
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
app.get('/search', async (req, res) => {
const fetchApi = await fetch(`https://www.googleapis.com/books/v1/volumes?q=${query}`)
const bookResponse = await fetchApi.json()
return bookResponse
})
CodePudding user response:
You need to specify the action
attribute to the html Form
<form id="submit" action="/search">
<label for="query">Enter Book Query</label><br>
<input type="text" id="query" placeholder="Search For Books!">
<input type="submit" value="Submit">
so that tells the form, where to send the data.
CodePudding user response:
I am Not giving you a direct answer to your problem... But I will suggest you to learn React and Axios. Your html pages will become just few lines of html code and React is for me much easier to use than just html.