Why NextJS can't connect to Microsoft Azure Cloud Function?

Pavlo Kozak 45 Reputation points
2023-05-19T19:18:34.37+00:00

When I try to make fetch to Microsoft Azure Cloud Function , I get code 500. If I open my cloud function url in the browser it gives me my response and works fine, and the authLevel is anonymous so everyone can make a request to this func.

TypeError: fetch failed

Error: connect ECONNREFUSED ::1:7071

API route:

export async function GET(request: Request) {
    try {
        // Connect to mcrft azure func endpoint
        const response = await fetch(
            `${process.env.VERCEL_URL || "http://localhost:7071"}/api/getChatGPTSuggestion`,
            {
                cache: "no-store",
            }
        );

        const textData = await response.text();

        return new Response(JSON.stringify(textData.trim()), {
            status: 200,
        });

    } catch (error) {
        console.log("error inside get route", error)

        if (error instanceof Error) {
            return new Response(error.message, { status: 500 });
        }

        return new Response("Internal Server Error", { status: 500 });
    }
}

Cloud function

const { app } = require('@azure/functions')

const openai = require('../../lib/openai')

app.http('getChatGPTSuggestion', {
  methods: ['GET'],
  authLevel: 'anonymous',
  handler: async (request, context) => {
    const response = await openai.createCompletion({
      model: 'text-davinci-003',
      prompt: '...',
      max_tokens: 100,
      temperature: 0.8, different and sharp
    })

    context.log(`Http function processed request for url "${request.url}"`)

    const responseText = response.data.choices[0].text

    return {
      body: responseText,
    }
  },
})
Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
4,609 questions
0 comments No comments
{count} vote

Accepted answer
  1. Pramod Valavala 20,611 Reputation points Microsoft Employee
    2023-05-24T18:54:56.1933333+00:00

    UPDATE: The problem here was that localhost is being resolved to its IPv6 address of ::1.

    Changing http://localhost:7071 to http://127.0.0.1:7071 instead did the trick.


    @Pavlo Kozak Based on the error log, looks like the requests is going to http://localhost:7071 instead of your cloud function.

    You should double check and ensure that the VERCEL_URL environment variable is being set correctly.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful