Encountering issues transferring form data from a SvelteKit server endpoint to formsubmit.co/ajax

Currently, I am developing a SvelteKit project that requires sending form data from a server endpoint to an external API called FormSubmit.co/ajax. While I can successfully send the form data directly from the client-side in a +page.svelte file, I have encountered difficulties when attempting to send the form data from a server endpoint (+page.server.ts). Even after deploying the web application to Vercel for troubleshooting, I keep encountering the following error:

{
  success: "false",
  message: "Make sure you open this page through a web server, FormSubmit will not work in pages browsed as HTML files."
}

In my +page.server.ts file, here is the code snippet I am using:

export const actions = {
  default: async ({ request }) => {
    const formData = await request.formData();
    const formValues = Object.fromEntries(formData);

    ...

    const response = await fetch('https://formsubmit.co/ajax/your-formsubmit-id', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json'
      },
      body: JSON.stringify(formValues)
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();

    if (data.success === 'false') {
      throw new Error(data.message);
    }

    return {
      status: 200,
      body: {
        success: true,
        resultMessage: 'The message was sent correctly'
      }
    };
  }
};

Additionally, this is the form setup within my +page.svelte page:

...
<form
        action="#"
        method="POST"
        use:enhance={() => {
            isLoading = true;
            return async ({ update }) => {
                await update();
                isLoading = false;
            };
        }}
        class="mx-auto mt-10 max-w-xl sm:mt-15"
    >
...

Despite reviewing the documentation and attempting multiple strategies to enable server-side submission, including testing on Vercel, I still face the same issue. Interestingly, when executing a simple fetch operation from +page.svelte, the email sends successfully. However, I am eager to achieve successful submission from +page.server.ts. Any insights or guidance on resolving this would be greatly appreciated. Thank you all in advance!

Answer №1

The issue at hand pertains to FormSubmit rather than SvelteKit.

FormSubmit anticipates that the request originates directly from a client-side form. It is possible that FormSubmit looks for specific browser-generated headers to authenticate submissions coming straight from a browser.

For more information, visit: Can't submit form with formsubmit.co AJAX API

Additionally, check out: https://formsubmit.co/help#:~:text=You%20may%20encounter%20an%20error,server%20like%20Apache%20HTTP%20Server.

One suggested workaround for executing server-side actions and transmitting data to FormSubmit is as follows:

export const actions: Actions = {
    default: async ({ cookies, request, url }) => {
        const formData = await request.formData();

        // Perform server side actions here
        // e.g. Store in DB

        // Redirect to a new page 
        // On this new page, use a hidden form to submit the data on page load
        return {
            status: 303, 
            headers: {
                 location: '/submit-form/confirmation',
            },
        };
    }
};

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

Proper application of this - encountering issues with property emit of undefined in Angular

I am working with an angular component and encountering the following code: @Output() fixPercentChanged = new EventEmitter<number>(); In addition, I have this event: fixChanged(e) { setTimeout(() => { let fix = e.component.option(&apo ...

Encountering a syntax issue with pipeable operators in Angular Rxjs

I am currently in the process of rewriting this code snippet: Observable .merge(this.searchQuery$, this.lazyQuery$) .do(() => this.loadingPage()) .map(filter => this.buildURL("jaume", Config.security['appName'], filter)) .s ...

Are React component properties enclosed in curly braces?

I have a new component configured like this: type customType = differentType<uniqueType1, uniqueType2, uniqueType3>; function customComponent({q}: customType) When called, it looks like this: <customComponent {...myCustomVar} />, where myCus ...

Activating Ionic6 Stack Modal through JavaScript or TypeScript

Is it possible to trigger the modal using script code instead of a button? I have searched through various examples in the tutorial, but all of them rely on the modal trigger mechanism. <ion-button id="open-modal" expand="block">O ...

An error occurred with the datepicker: Unable to connect to 'bsValue' as it is not recognized as a property of 'input'

Despite importing DatepickerModule.forRoot() in my Angular unit test, I am encountering the following error: Error: Template parse errors: Can't bind to 'bsConfig' since it isn't a known property of 'input'. (" ...

The tsconfig within the module directory fails to supersede the extended tsconfig properties present in the parent directory

Within the directory store/aisle/fruits, there is a tsconfig.json file: { "compileOnSave": true, "compilerOptions": { . . "target": "es6", "noEmitOnError" : true, "noEmitHelpers ...

When setupFilesAfterEnv is added, mock functions may not function properly in .test files

Upon including setupFilesAfterEnv in the jest.config.js like this: module.exports = { preset: 'ts-jest', testEnvironment: 'node', setupFilesAfterEnv: ["./test/setupAfterEnv.ts"] } The mock functions seem to sto ...

Steps to creating a Partial Pick attribute

I'm facing an issue with a function I have function someThing(someArg: Pick<HTMLElement, 'id' | 'style'>) {...} The problem is that I only want to apply certain styles to someArg.style, not all the styles from CSSStyleDecla ...

What are the steps for importing a file into a React app that is built using Create React App as plain text?

Objectives I aim to showcase code snippets from the project itself for reference. I intend to keep the displayed code up-to-date with its implementation. I prefer not to remove myself from create-react-app This React project, built using create-react-ap ...

Solving the issue of "Property does not exist on type 'never'" in a program involves identifying the root cause of

Issue An error message related to .cropper is occurring with the code snippet below. Error Message The property 'cropper' does not exist on type 'never'. Query How can I resolve the error associated with type 'never'? B ...

Is there a method to reduce the requirement for if-conditions in this situation?

After revisiting this previous inquiry, I successfully implemented multiple filters on my observable, based on the user's chosen filters. However, the issue arises from the uncertainty of whether a filter is applied and the varying behavior of each f ...

In React Typescript, there is an issue with react-router v4 where the Route component does not pass its props to the specified component

Struggling with React Router v4 and history usage in Browserrouter. Whenever attempting to access this.props.history.push("/"), the error pops up: TS2339: Property 'history' does not exist on type 'Readonly<{ children?: ReactNode; }> ...

What is the best way to transform a string array into a number array?

I'm attempting to convert a string array into a number array and after conducting some research online, I came across this solution: let numbersAsStringArray = originalQueryParams[property] ?? [] let numbers = numbersAsStringArray.map((i) => ...

What is the proper way to invoke a child method after converting an object from a parent class to a child class?

When we have a subclass B that overrides a method from its superclass A in TypeScript, why does calling the method on an instance of A result in the parent class's implementation being called? In TypeScript, consider a class called Drug with properti ...

Can I retrieve the return type of useFetch in Nuxt3?

I am running into an issue while trying to specify the APIBody type in the following manner: Property 'test' does not exist on type 'NonNullable<PickFrom<_ResT, KeysOf>>'. It seems like there is no straightforward way to def ...

Error message: "The property is not found within the specified type when using the OR operator with

Within my Angular component, I am faced with a challenge involving an Input that can be one of two types. @Input() profile: UserProfileDetails | BusinessProfileDetails; The structure of the profile template is straightforward and I want to avoid duplicati ...

Trouble with modifying a cell in a TypeScript office script

Hello everyone. I am in need of a code that can track which cells are active or selected, and then block them once a user is no longer interacting with them. I understand that there may be some issues, especially if the user selects a cell but does not ma ...

The letter 'X' is not suitable for use as a JSX component because its return type 'Element[]' does not qualify as a valid JSX element

Currently, I am working on rendering two simple joke cards in TypeScript. The cards are displaying correctly in my browser, but I've encountered an error message that says: 'Jokes' cannot be used as a JSX component. Its return type 'Ele ...

The data type 'string | null | undefined' cannot be assigned to the data type 'string | undefined'

In my Angular application using Typescript, I have the following setup: userId?: number; token?: string; constructor(private route: ActivatedRoute) { this.route.queryParamMap.subscribe( (value: ParamMap) => { this.userId = val ...

Creating a carousel with material design aesthetics

I'm working on implementing a carousel in my setup using Angular CLI: 6.0.5, Node: 10.1.0, OS: win32 x64, and Angular: 6.0.3. However, I haven't been able to locate documentation for creating the carousel in Angular's Material Design framewo ...