skip to Main Content

I want to trigger a client side function Javascript, with Nodejs
I’m trying to get a response from the Nodejs to display data on my website

A program will send an API to my Nodejs Api example(htpp://localhost:3000/apiResponse) containing some data
I want to get the API data to my frontend

How can i do this, or is there another way to trigger a function o value when a API send to me?

2

Answers


  1. You can use the browser native fetch function to call your API:

    fetch('http://localhost:3000/apiResponse')
      .then(response => response.json())
      .then(json => console.log(json))
    

    or

    const main = async () => {
      const json = await (await fetch('http://localhost:3000/apiResponse')).json();
      console.log(json);
    };
    
    main();
    
    Login or Signup to reply.
  2. If I understood your situation correctly, this is how I would handle it.

    1. Create a function in your front-end that makes a request to your local node server. The function is asynchronous because we’re not sure how long the server will take to respond. Then you could call the function inside of a button click, for example.
      const handleGetResponse = async () => {
        let data = {};
        try {
          const response = await fetch("htpp://localhost:3000/apiResponse").then(res => res.json())
            data = response;
            console.log("%cdata:", data);
        } catch(error) {
          console.log(error);
        }
      }
    
    1. Create a function in your node file that handles the response
    const nodeHandleResponse = () => { // handle response };
    
    1. In the same node file, create a path to receive the front-end request, & call the node function that handles the response. Then, send the response to your front-end.
    app.get("/apiResponse", async (req, res) => {
      nodeHandleResponse().then(response => res.send(response))
    });
    

    Note how the request url from the front-end is the same as the node GET path -> "apiResponse". I hope this helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search