#Why do I get this error?

1 messages · Page 1 of 1 (latest)

round inlet
#

@dry matrix

const allLinks = document.querySelectorAll(".content a");
        let linkHref = Array.from(allLinks, link => link.href);

        (async () => {
            try {
                const response = await fetch("/api/hello", {
                    method: "PvoisOST",
                    body: JSON.stringify(linkHref)
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const data = await response.json();
                console.log(data);
            } catch (error) {
                console.error("Error fetching data:", error);
            }
        })();

This is my code but now I get from the api endpoint status code 400 bad request... any ideas?

dry matrixBOT
#

Hi @round inlet. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

It seems like there might be an issue with your API request. Based on the provided code, I noticed that the method is set to "PvoisOST" which is not a valid HTTP method. You should use a valid method like "POST" instead. Here's the corrected code:

const allLinks = document.querySelectorAll(".content a");
let linkHref = Array.from(allLinks, link => link.href);

(async () => {
    try {
        const response = await fetch("/api/hello", {
            method: "POST",
            body: JSON.stringify(linkHref)
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.error("Error fetching data:", error);
    }
})();

Make sure your API endpoint at /api/hello is set up to handle the POST request and process the data accordingly. If you still encounter issues, you might want to check the server-side code for handling the request and sending the appropriate response.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@round inlet kapa.ai is still learning and improving, please let us how it did by reacting below

round inlet
#

@dry matrix

import {NextResponse} from "next/server";

// Info That I can use the requests content the function has to be async and the answer needs await until it's there
export async function GET() {
    return new Response("nothing to see here ;)");
}

export async function POST(req, res) {
    try {
        const URLs = await req.json();
        const statuses = [];

        await Promise.all(
            URLs.map((link) =>
                fetch(link)
                    .then((resp) => {
                        console.log(resp.status + " " + link);
                        statuses.push({ url: link, status: resp.status });
                    })
                    .catch((error) => {
                        console.log(error)
                        statuses.push({ url: link, status: "error" });
                    })
            )
        );
        return NextResponse.json(statuses)
    } catch (error) {
        console.error("Error occurred:", error);
        res.status(500).json({ message: "An error occurred while processing the request." });
    }
}

This is the code from the api endpoint. any suggestions where the problem is?

dry matrixBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Your API endpoint code looks mostly correct, but there's a small issue with the error handling. Instead of using res.status(500).json(...), you should use NextResponse to return the error response. Here's the corrected code:

import { NextResponse } from "next/server";

export async function GET() {
  return new Response("nothing to see here ;)");
}

export async function POST(req, res) {
  try {
    const URLs = await req.json();
    const statuses = [];

    await Promise.all(
      URLs.map((link) =>
        fetch(link)
          .then((resp) => {
            console.log(resp.status + " " + link);
            statuses.push({ url: link, status: resp.status });
          })
          .catch((error) => {
            console.log(error);
            statuses.push({ url: link, status: "error" });
          })
      )
    );
    return NextResponse.json(statuses);
  } catch (error) {
    console.error("Error occurred:", error);
    return NextResponse.error(500, "An error occurred while processing the request.");
  }
}

Now, the error response will be handled correctly using NextResponse.error(). If you still encounter issues, make sure to check the client-side code and ensure that the request is being sent correctly.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@round inlet kapa.ai is still learning and improving, please let us how it did by reacting below

round inlet
#

@dry matrix

const [data, setData] = useState(null)
    const [error, setError] = useState(null)

    useEffect(() => {
        document.getElementById("locationSubmit").addEventListener("click", submit);
        document.getElementById("sendLinksButton").addEventListener("click", validateLinks);

        const APIAddress = '/api/hello';
        const swrParameters = {
            revalidateOnFocus: false,
            revalidateOnMount: false,
            revalidateOnReconnect: false,
            refreshWhenOffline: false,
            refreshWhenHidden: false,
            refreshInterval: 3600,
        }
        
        // copy all links so that they are visible for the end user for easier checkup
        const allLinks = document.querySelectorAll(".content a");
        let linkHref = Array.from(allLinks, link => link.href);

        async function validateLinks()  {
            try {
                const response = await fetch("/api/hello", {
                    method: "POST",
                    body: JSON.stringify(linkHref)
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const {SWRData, SWRError} = useSWR(APIAddress, response, swrParameters)

                setData(await SWRData.json());
                console.log(data);
            } catch (error) {
                console.error("Error fetching data:", error);
            }
        }

Given this copied snipped of code react tells me I'm breaking the concept of hooks. Have you an idea whats wrong?

dry matrixBOT
#

Let me check the knowledge base for you. One moment! :books:

#

The issue with your code is that you're using the useSWR hook inside the validateLinks function, which is not allowed. Hooks should be called at the top level of your component and not inside functions, loops, or conditions. You can refactor your code to use useSWR correctly and handle the data fetching logic.

Here's a modified version of your code:

import useSWR from 'swr';

// Inside your component
const [data, setData] = useState(null);
const [error, setError] = useState(null);

const APIAddress = '/api/hello';
const swrParameters = {
  revalidateOnFocus: false,
  revalidateOnMount: false,
  revalidateOnReconnect: false,
  refreshWhenOffline: false,
  refreshWhenHidden: false,
  refreshInterval: 3600,
};

const { data: SWRData, error: SWRError } = useSWR(APIAddress, swrParameters);

useEffect(() => {
  document.getElementById('locationSubmit').addEventListener('click', submit);
  document.getElementById('sendLinksButton').addEventListener('click', validateLinks);

  // copy all links so that they are visible for the end user for easier checkup
  const allLinks = document.querySelectorAll('.content a');
  let linkHref = Array.from(allLinks, (link) => link.href);

  async function validateLinks() {
    try {
      const response = await fetch('/api/hello', {
        method: 'POST',
        body: JSON.stringify(linkHref),
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      setData(await response.json());
      console.log(data);
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  }
}, []);
#

In this modified version, the useSWR hook is called at the top level of your component, and the data fetching logic is handled inside the validateLinks function. This should resolve the issue with breaking the concept of hooks.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: