What is preventing NextJS API route from being able to fetch from Microsoft Azure Cloud Function?

Whenever I attempt to retrieve data from the specified URL, I encounter an error. The URL and port are accurate, as opening the URL in a browser yields the expected response. However, attempting to connect to it via the API route results in everything breaking down.

The error message reads:

TypeError: fetch failed

at Object.fetch (node:internal/deps/undici/undici:14062:11)

at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

{ cause: Error: connect ECONNREFUSED ::1:7071

at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1487:16) at

TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {

errno: -4078,

code: 'ECONNREFUSED',

syscall: 'connect',

address: '::1',

port: 7071 } }

Within the 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 });
    }
}

Regarding the 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,
    })

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

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

    return {
      body: responseText,
    }
  },
})

Answer №1

The address: '::1' mentioned in the error message suggests an attempt to connect to localhost.

The IPv6 localhost address is 0000:0000:0000:0000:0000:0000:0000:0001, and can be shortened to ::1

It seems that process.env.VERCEL_URL is not configured properly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Traversing a series of HTML form elements in order to extract their current values and store them in an object

Suppose we have an HTML structure like this: <nav data-filters class=""> <input type="radio" name="type" value="company" checked>Company <input type="radio" name="type" value="product">Product <input type=" ...

Comparison between HighChart, D3.Chart, and C3.Chart

In need of charting capabilities for my CMS Application. I am interested in incorporating Pie Charts, Area Charts, Column Charts, Bar Charts, and Gauge Charts. After doing some research online, C3.js and HighCharts.js stood out to me as promising options. ...

Using ReactJS to return a component from a function

Working with React, useState, and React-Icons. I am trying to implement a dropdown menu without using Bootstrap. My goal is to change the icon upon clicking to trigger a function, but currently, it only displays the raw SVG details. Any suggestions on how ...

Puppeteer experiencing issues with missing relative modules and dependencies not being found

After installing puppeteer via npm, I encountered errors when trying to compile it: This dependency was not found: * ws in ./node_modules/puppeteer/lib/WebSocketTransport.js To resolve this, you can run: npm install --save ws These relative modules we ...

Issues encountered with implementing a custom search feature using AJAX in jQuery UI Autocomplete

Here is the response from my JSON data: [{"value":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c4a5a0a9adaa84a5a0a9adaaeaa7aba9">[email protected]</a>"},{"value":"<a href="/cdn-cgi/l/email-protection" class ...

Conceal Bootstrap 3 Modal and AngularJS navigation using $location.path

In my AngularJS App, I am utilizing the Bootstrap 3 modal as a dialog confirmation. However, when I hide the modal and redirect, the backdrop of the modal still remains visible. $scope.delete = function () { DataService.delete() .then(function () ...

Using jQuery to refresh a div element

I am struggling with updating the "right" div in my jsp page using the script below. Despite being contained in a single file, the update does not seem to work. Any assistance is appreciated. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//E ...

Converting a timestamp to a date format such as "Jan 2" or "Jan 26" using JavaScript and jQuery

If you have a string in the format: Sun Feb 06 2011 12:49:55 GMT-0800 (PST) Is there a way to convert it to: Feb 6 And / Or Sun Jan 26 2011 12:49:55 GMT-0800 (PST) to: Jan 26 Do you have any suggestions? ...

Guide on incorporating interactive visuals or features within a panoramic image viewer through the use of THree.js and webGL

Seeking advice on how to incorporate more images and hyperlinks within a panoramic viewer, similar to the examples below: This particular link Panorado js viewer. I have noticed that these viewers feature embedded hyperlinks and overlays, I have attempt ...

Creating a system for handling multiple users in my to-do app with MERN stack: What is the best approach

Currently, I am working on adding a feature that would allow multiple users to use my to-do app. However, I am uncertain about the most effective way to do this. Essentially, I want users to be able to create accounts, log in, and have access to their own ...

Error: Unable to locate the include file

Hello, I am currently a student working on a project where I am attempting to retrieve a list of books from the server and display them one by one using ejs. Here is an overview of my project structure: | |-----routes | |-----index.js |-----vie ...

CSS: Problem Arising from Line Connections Between Tree Elements

I'm currently working on connecting tree nodes with lines in a drawing. I've managed to achieve it to some extent, but there are a few issues like dangling lines that I need to fix. You can find the implementation on codepen here: https://codepe ...

Using the jqueryRotate plugin to rotate an image by 90 degrees

Is there a way to rotate images on a webpage using the JQueryRotate script? I have 10 images that I want to be able to rotate when clicked, but I'm not sure how to implement it. Any assistance would be welcomed. This is the HTML code for the images: ...

Encountering a 404 server error on Azure Node.js web app while running AngularJS 1.6.x with lengthy URLs

My current setup includes two azure web apps deployed with a node.js express server and using angularjs (1.6.x) for the MVC (ui-router). One web app links directly to the other, passing an access token in the query params for authentication. Everything run ...

Guide on Capturing Szimek/Signature_Pad using PHP: How to Save Javascript as PHP Variable?

While perusing through StackOverflow, I stumbled upon Szimek/Signature_Pad which allows for the capturing of electronic/digital signatures using Javascript. Even after conducting research, I still find myself puzzled on how to capture the DATA URI into a ...

How can I implement a transition when changing the setClearColor property of the WebGL Renderer in three.js?

const glRenderer = new THREE.WebGLRenderer({antialiasing: true, alpha:true}); glRenderer.setClearColor(0x000000); I am looking to implement a smooth transition or tween for changing the clear color from the current one to a new color ...

Learn the process of dynamically updating the source of an HTML5 video

Currently, I am working on a project that involves dynamically loading multiple videos onto a webpage. The structure of my HTML is quite straightforward - it consists of a single video tag. <video controls preload width="520" height="350" id="video"> ...

The most effective method for positioning a child element to the left and top using Flexbox grid

I am currently working on visualizing queues and processes within a system. Each process is associated with a specific queue from which it retrieves data. I aim to create a layout similar to the following: https://i.stack.imgur.com/BXyts.png However, I a ...

When a node_module package includes type imports, Next.js can encounter build failures during the linting and type validity checking processes

This NextJS 13 project utilizes a package that has an inner core dependency (react-leaflet->@react-leaflet/core). When running yarn run build, the build fails at "Linting and checking validity of types." It appears to be a TypeScript compatibility iss ...

The HTTP post method is mistakenly perceived as the HTTP get method

I was working on a JavaScript snippet that looks like this: $.ajax({ type: "Post", contentType: 'application/json', url: "../api/Pointage/GetPointages", data: JSON.stringify({ ...