Giter Site home page Giter Site logo

Comments (3)

karlhorky avatar karlhorky commented on August 11, 2024

I think this may be actually 2 bugs though:

  1. fetch-jsonp calls resolve() and removes the script on the first usage of the function
    window[callbackFunction] = (response) => {
    resolve({
    ok: true,
    // keep consistent with fetch API
    json: () => Promise.resolve(response),
    });
    if (timeoutId) clearTimeout(timeoutId);
    removeScript(scriptId);
    clearFunction(callbackFunction);
    };
  2. A Mailchimp bug, that they are not including a semicolon between the function calls (or maybe , or || or && instead, if it's supposed to be a JavaScript expression)

from fetch-jsonp.

karlhorky avatar karlhorky commented on August 11, 2024

Looking into JSONP more, it seems like it's pretty standard to have only a single function call.

@camsong So if that's the convention, I'm happy to have this issue closed - because it would be only that Mailchimp is breaking that convention.

from fetch-jsonp.

karlhorky avatar karlhorky commented on August 11, 2024

To work around this issue, we ended up writing our own Next.js Route Handler which passes along the request query parameters and fixes the Mailchimp response (only shows the first error):

app/api/mailchimp-subscriptions/route.ts

import { NextRequest, NextResponse } from 'next/server';

type MailchimpSubscriptionsResponseBodyGet = string;

// Fix broken Mailchimp JSONP responses (double function calls)
// https://github.com/camsong/fetch-jsonp/issues/72#issuecomment-2220956128
export async function GET(
  request: NextRequest,
): Promise<NextResponse<MailchimpSubscriptionsResponseBodyGet>> {
  const url = new URL(request.url);

  url.hostname = 'xxx.us20.list-manage.com';
  url.pathname = '/subscribe/post-json';
  url.port = '';

  const searchParams = request.nextUrl.searchParams;
  const callbackFunctionName = searchParams.get('c');

  try {
    const response = await fetch(url.toString());

    if (!response.ok) {
      return new NextResponse(
        `${callbackFunctionName}({"result":"error","msg":"Invalid response status"})`,
      );
    }

    const textResponse = await response.text();

    const firstJsonpFunctionCall = textResponse.match(
      new RegExp(`^${callbackFunctionName}\\(\\{[^}]+\\}\\)`),
    );

    if (!firstJsonpFunctionCall) {
      return new NextResponse(
        `${callbackFunctionName}({"result":"error","msg":"Invalid response format"})`,
      );
    }

    return new NextResponse(firstJsonpFunctionCall[0], {
      headers: {
        'Content-Type': 'application/javascript',
      },
    });
  } catch (error) {
    return new NextResponse(
      `${callbackFunctionName}({"result":"error","msg":"${(error as Error).message}"})`,
    );
  }
}

Then just change your call to fetchJsonp() to use the new Route Handler instead of Mailchimp directly:

const response = await fetchJsonp(
-  `https://xxx.us20.list-manage.com/subscribe/post-json?u=xxx&amp;id=xxx&${new URLSearchParams({ EMAIL: email }).toString()}`,
+  `/api/mailchimp-subscriptions?u=xxx&amp;id=xxx&${new URLSearchParams({ EMAIL: email }).toString()}`,
  {
    jsonpCallback: 'c',
  },
);

from fetch-jsonp.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.