1

I have simple REST API that works by making queries to Postgresql DB. How do i write button, that onClick activate GET function and shows it on webpage? How to do it with POST requests? How to link app.js file to index.html, so it identifies names of functions from app.js? How to make div that will accept POST requests? Do i need some html functions to handle PUT and DELETE requests?

app.post('/tourists', async(req, res, err) => {

    let dbResult=[];
    for (let i=0;i<req.body.listofflightsbyid.length;i++) {
        try {
            let result = await callDB( "SELECT flights.id FROM flights WHERE flights.id = " + req.body.listofflightsbyid[i] );
            dbResult.push(result);
        }
        catch (err) {

            console.log("Flight with id " + req.body.listofflightsbyid[i] + " you want to add to list of flights does not exist");
            res.status(500);
            return res.send("Bad listofflightsbyid request, Flight with id " + req.body.listofflightsbyid[i] + " does not exist");

        }
    }

    console.log("Successfully fetched all records ", dbResult);
    res.status(200);
    return res.send(dbResult);
})

1 Answer 1

1

There are many questions here! You will likely receive better answers if you take the time to divide your concerns into separate, more specific questions, and ask them again. But, I suspect most of your questions already have answers here on StackOverflow.

Event Binding

Assuming you're using vanilla JavaScript (no external libraries, frameworks and so forth), and assuming you have a <button> element and a function called myFunction somewhere, you can bind your function to the button's click event two ways.

You can bind events inline:

button.html

<button onclick="myFunction()">Click</button>

Or you can bind events programmatically:

button.html

<button id="click">Click</button>
<script src="button.js"></script>

button.js

document.getElementById('click')
  .addEventListener('click', myFunction);

AJAX

I would suggest using the Fetch API (a usage guide, if that helps) to communicate with your backend using AJAX, or Asynchronous JavaScript and XML. In spite of the name, AJAX is not limited to working with XML.

Unlike XMLHttpRequest, the Fetch API is Promise-based.

A minimal GET request that expects a JSON response:

const url = 'https://...';

fetch(url, {
  method: 'GET',
  headers: {
    'Accept': 'application/json'
  }
})
.then(response => {
  if (response.ok) {
    // if the response status is in the 200-299 range
    return response.json();
  }

  // handle your application error state
})
.catch(error => {
  // handle network errors
  console.error(error);
});

Do note that, in the Fetch API, 4XX and 5XX error responses are not considered error states, which is why the additional handling for adequate responses may become necessary. The Fetch API only throws on network errors.

A minimal POST request that sends JSON and expects a JSON response:

const url = 'https://...';

fetch(url, {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ })
})
.then(response => {
  if (response.ok) {
    // if the response status is in the 200-299 range
    return response.json();
  }

  // handle your application error state
})
.catch(error => {
  // handle network errors
  console.error(error);
});

Script-level Scoping

Include the script file as a static resource served by your backend (look into ExpressJS's static middleware) and include it in your frontend HTML:

index.html

<script src="app.js"></script>

If you want to write isomorphic JavaScript (code used on both the client and the server) you'll need to take some additional, advanced steps to handle that. I don't have adequate experience configuring the build pipelines necessary to comment further on this subject. Consider looking into Webpack or Rollup.

DOM Manipulation - Displaying the result of AJAX requests

Make an AJAX request, then use client-side JavaScript to interact with the DOM. Assuming the request below returns a JSON Array of people Objects who all have a name property, this will create a new <p> element containing each person's name and inject it into a <div> with an id of #my-div on the current page:

const url = 'https://...';

fetch(url, ...)
  .then(json => {
    const div = document.getElementById('my-div');

    json.people.forEach(person => {
      const p = document.createElement('p');

      p.innerText = person.name;

      div.appendChild(p);
    });
  });

PUT & DELETE Requests

Using the Fetch API, you may specify any HTTP verb you please:

const url = 'https://...';

fetch(url, {
  method: 'DELETE'
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.