79216278

Date: 2024-11-22 19:05:36
Score: 0.5
Natty:
Report link

I have a problem trying to use google maps api in nextjs.

The problem is that I can't access the path where I have my search.tsx file. I get a 404 error in console, and in postman, using the path http://localhost:3000/api/search I also get a 404 error. I share with you my codes and my file organization, I appreciate any help! :)

page.tsx:

        for (const category of selectedCategories) {
      try {
        const response = await fetch("../api/search", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            location,
            category,
            filters: {
              minRating,
              minReviews,
              businessHours,
              ...filters,
            },
          }),
        });

        if (!response.ok) {
          throw new Error(
            `API request failed with status ${response.status}`
          );
        }

        const data: SearchResponse = await response.json();

        if (!data.success) {
          throw new Error(data.error || "Failed to fetch leads");
        }

        const leads = data.results;

        // Update count for each
        setExtractedLeadsCount((prev) => prev + leads.length);

        // Add leads to array with additional metadata
        const processedLeads = leads.map((lead) => ({
          ...lead,
          category,
          searchLocation: location,
          extractedAt: new Date().toISOString(),
        }));

        allLeads = [...allLeads, ...processedLeads];
      } catch (error) {
        toast({
          title: "Error",
          description: `Failed to fetch ${category} in ${location}: ${error.message}`,
          variant: "destructive",
        });
        continue;
      }
    }

Search.tsx:

    import { NextApiRequest, NextApiResponse } from 'next';
import fetch from 'node-fetch';

interface GooglePlacesResponse {
    results: any[];
    status: string;
    error_message?: string;
}

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
    if (req.method === 'POST') {
        const { location, category } = req.body as { location: string; category: string };

        try {
            const response = await fetch(
                `https://maps.googleapis.com/maps/api/place/textsearch/json?query=${encodeURIComponent(category)}+in+${encodeURIComponent(location)}&key=APIKEY`
            );
            const data: GooglePlacesResponse = await response.json();

            res.status(200).json(data); // Devuelve los datos obtenidos
        } catch (error) {
            console.error("Error fetching data from Google Places:", error);
            res.status(500).json({ error: "Error fetching data" });
        }
    } else {
        res.setHeader('Allow', ['POST']);
        res.status(405).end(`Method ${req.method} Not Allowed`);
    }
};

export default handler;
Reasons:
  • Blacklisted phrase (1): any help
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Emiliano Velázquez