The API for /api/campaign/dynamicid has been resolved but no response was sent, potentially causing delays in processing requests within Next.js

Encountering a problem with my Amazon SES code in Next.js. Unsure where the mistake lies, seeking assistance to resolve the error. Feel free to ask if you have any questions.

sendmail.js

This is where I encountered an issue in the sendmail.js file while utilizing Amazon SES for email delivery.

var AWS = require('aws-sdk');

AWS.config.update({ region: process.env.AWS_REGION });

// var mail = '';

function sendMail(Email) {

    var result;
    // Create sendEmail params 
    var params = {
        Destination: { /* required */
            CcAddresses: [
                Email,
                /* more items */
            ],
            ToAddresses: [
                Email,
                /* more items */
            ]
        },
        Message: { /* required */
            Body: { /* required */
                Html: {
                    Charset: "UTF-8",
                    Data: "HTML_FORMAT_BODY"
                },
                Text: {
                    Charset: "UTF-8",
                    Data: "TEXT_FORMAT_BODY"
                }
            },
            Subject: {
                Charset: 'UTF-8',
                Data: 'Test email'
            }
        },
        Source: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f3e3d3c1f38323e3633713c3032">[email protected]</a>', /* required */
        ReplyToAddresses: [
            '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="26474445171466414b474f4a0845494b">[email protected]</a>',
            /* more items */
        ],
    };

    // Create the promise and SES service object
    var sendPromise = new AWS.SES({ apiVersion: '2010-12-01' }).sendEmail(params).promise();

    // Handle promise's fulfilled/rejected states
    sendPromise.then(
        function (data) {
            result = 'Success';
        }).catch(
            function (err) {
                result = 'Failed';
            });
}

export default sendMail;

dynamicid.js

This is where I implemented my endpoint code in the dynamic id.js file.

import { getDataFromSheets } from '../../../libs/sheets';
import sendmail from '../../../libs/ses/sendmail';

export default function handler(req, res) {
  var data;
  getDataFromSheets()
    .then(sheet => {
      data = sheet.length
      for (var i = 1; i < data; i++) {
        sendmail(sheet[i].Email)
      }
    })
    .catch(err => console.log(err))

}

Answer №1

To properly conclude the request-response cycle, it is imperative that every endpoint function includes a response mechanism such as res.send(), res.json(), or res.end(). The following code provides a solution:

const handleRequest = (req, res) => {
  let data;
  
  fetchDataFromAPI()
    .then(apiData => {
      data = apiData.length;
      
      for (let i = 0; i < data; i++) {
        sendNotification(apiData[i].email);
      }
      
      res.json({status: 'success', message: 'Email notifications sent'});
    })
    .catch(error => {
      console.log(error);
      res.json({status: 'fail', error: error});
    });
};

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

Ways to use jQuery to disable row form elements in the second and third columns

I need a way to deactivate form elements in the second and third columns, starting from the second row until the nth row using a jQuery selector. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/> ...

Form Validation in JavaScript Continues to Submit Form Even When 'False' is Detected

Here is the issue at hand - I am restricted to using older browsers (IE8 and FF8) by corporate policy. Despite my research indicating otherwise, it seems like this might be the root cause of my troubles. My current setup includes PHP 5.5.12 on Apache 2.4. ...

Is it beneficial to utilize both revalidatePath and Return Value in a Server Action?

Looking for some assistance Description: I am utilizing useFormState with a server action. However, when I include both revalidatePath and a return value, the revalidatePath functions correctly but does not return any value state for useFormState. When I r ...

Creating a Texture in html5 and WebGL using an ArrayBuffer

I have an image that I am retrieving on the server side and sending to the web browser through an AJAX call. I need to display this image line by line using WebGL. For example, let's consider an image with dimensions 640X480. This means there are a t ...

Issue encountered while presenting canvas on HTML due to Firebase information

Even though I believe I'm following the correct steps, I am facing an issue where the graph displaying real-time database values is not showing up. The first image shows my real-time database and a demostration as shown in images 2 and 3. While the da ...

Transform a dynamic web page into a static one using Next.js

Utilizing Next.js and React.js, I create dynamic web pages. Specifically, I generate user-related web pages that need to be updated when there are changes in the user data. How can I generate static HTML pages from this updated data within Next.js? Are the ...

Activate the script upon the left-click of the arrow icon

Looking for help with this basic javascript code snippet. $('#about_us').on('click',function() { $('#slider').toggleClass('open'); }); I'm trying to find a way to activate this function by pressing the lef ...

Storing input values in the state using Typescript by default

Upon launching, my activeField state is initially empty. However, when a user focuses on the field, it gets added to the state. I am encountering a warning in Typescript because when I attempt to update the selectionEnd of that field, it tells me: Property ...

What is the best way to steer a vehicle in the desired direction by utilizing the arrow keys on the keyboard?

Image1 Image2 While using visual studio code, I noticed that I can move a car forwards and backwards with the arrow keys on the keyboard. However, it doesn't seem to turn when I try to move in opposite directions. Is there a way to achieve this thro ...

What is the best way to display the absent months in a mongo aggregate query with a value of 0?

Is it possible to ensure that the missing months in the aggregate result have a BruteAmount value of zero? Purpose This code aims to generate two arrays containing the month names and their respective BruteAmounts. The data should be ordered by the curre ...

Material UI does not support the inline attribute for applying CSS properties

Trying to adjust the CSS for Material-UI When setting the width, everything works fine. However, when attempting to set display inline, an error occurs ---> "inline is not defined" Can anyone provide guidance on how to resolve this issue? Sharing my cod ...

Does the Karma Tast Runner function on node js version 0.12.0?

I'm experiencing an issue where I have Node.js v0.12.0 installed with Karma on my OS X Yosemite, but when I try to run my test task using Gulp, it just hangs as shown in the picture. It seems like PhantomJS is not starting. Interestingly, the same cod ...

Attempting to deserialize serialized data from Django using JSON.parse

I need assistance with some client-side tasks using Javascript. In my view, I serialize a Queryset from my models into JSON and pass it to the template. data = serializers.serialize("json", Profile.objects.filter(user_id=self.request.user)) This results ...

The occurrence of an unanticipated character '#' was found

I'm currently facing an issue while using webpack to load dependencies. Whenever I execute the npm run dev command, I encounter the following error: Uncaught Error: Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError: ...

Updating form fields within nested forms using the FormBuilder array

The recommended method to change nested values according to the API documentation is using patchValue. For example, myForm.patchValue({'key': {'subKey': 'newValue'}}); But what if we need to change values in a nested array, ...

How to assign attributes to multiple menu items in WordPress without using JavaScript

I'm currently working on adding attributes to each item in my WordPress navbar. Here is what I have at the moment: <ul id="menu-nav-bar" class="menu"> <li><a href="#text">text</a></li> <li><a href="#car ...

How exactly does the NextAuth User Password implementation function?

I am currently working on implementing user authentication using NextAuth with email only. My goal is to have users register an account, receive an account verification email, and then successfully register. It seems that using NextAuth would be the most c ...

The save changes feature is not effectively syncing with the database

So, I have a button that triggers a javascript function, which initiates an AJAX request to call an actionresult that is supposed to update my database. Javascript Function function changeDepartment() { // Initializing and assigning variables va ...

"Looking to spice up your website with a dynamic background-image

I've encountered a problem with my CSS code for the header's background image. Despite trying various methods to create a slideshow, nothing seems to be working. Can someone provide guidance? I have four banner images named banner1, banner2, bann ...

Retrieve information using the request npm package

Currently, I am in the process of developing an application with express js. My approach involves using request(v-2.88.2) to retrieve data from an api. request(url, function(error, request, body) { var data = JSON.parse(body); }); My goal is to utili ...