Javascript - The preflight request response fails the access control check

I followed the instructions in the documentation to create a checkout session for stripe, but I encountered the following error:

Access to fetch at 'https://subdomain' from origin 'https://main-domain' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Where and how do I add the necessary header?

This is the request that is sent when the checkout button is clicked:

<script type="text/javascript">
   var stripe = Stripe('api key');
   var checkoutButton = document.getElementById('checkout-button');
   
   checkoutButton.addEventListener('click', function() {
     fetch('https://subdomain/create-session', {
       method: 'POST',
       headers: new Headers({
       'Authorization': 'Basic',
       'Access-Control-Allow-Origin': '*'
       })
     })
     .then(function(response) {
       return response.json();
     })
     .then(function(session) {
       return stripe.redirectToCheckout({ sessionId: session.id });
     })
     .then(function(result) {
       if (result.error) {
         alert(result.error.message);
       }
     })
     .catch(function(error) {
       console.error('Error:', error);
     });
   });
</script>

This is my express route:

app.post("/create-checkout-session", async (req, res) => {
    const session = await stripe.checkout.sessions.create({
        payment_method_types: ['card'],
        line_items: [
            { price: 'stripe product id', quantity: 1 },
            { price: 'stripe product id', quantity: 1 }
        ],
        mode: 'payment',
        success_url: 'https://site/success.html',
        cancel_url: 'https://site/cancel.html',
    });
    res.json({ id: session.id });
});

Answer №1

Make sure the header is part of the server's response, not the client's request. When utilizing express, you have the option to incorporate the CORS middleware to achieve this.

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

AngularJS - dynamically displaying updated content based on dropdown selection

I have implemented two dropdown lists using the select tag. I want to dynamically update the options in the second dropdown based on the selection from the first dropdown, and then display relevant information underneath based on the selection from the sec ...

What is the standard character-encoding for HTTP header values when using AJAX?

Let's say I am utilizing AJAX to send a request to a server in this manner: $.ajax( { url: url, beforeSend: function (request) { request.setRequestHeader('X-Test', 'one'); }, }); The documentation for $.aj ...

Uploading images simultaneously while filling out a form

Currently, I have a form that requires users to fill it out and upload an image. However, there is a delay of up to 30 seconds when the user hits "Submit" due to the image size being uploaded. I'm interested in finding a way to initiate the image upl ...

Unable to perform a POST request and send JSON data using AJAX with jQuery at the

It seems like there may be a server issue causing this problem, and unfortunately, I don't have access to our server to troubleshoot. I was hoping that someone else might have a solution or could help me understand the root cause of the issue. The is ...

CustomJS TextBox callback to adjust range of x-axis: Bokeh

I'm currently working on a web page that features a plot powered by an AjaxDataSource object. However, I am facing a challenge with implementing a TextInput widget that can modify the xrange of this plot. Here is a snippet of my code: source = AjaxDa ...

Display the user's username on the navigation bar once they have successfully

I am having trouble displaying the username after logging in on the navbar. After logging in with the correct credentials, I am redirected to the page, but the navbar doesn't update with the username. Can someone provide some tips on what I should do ...

Troubleshooting problems with the width of a Bootstrap navbar

I'm encountering a frustrating issue with my bootstrap menu. When I include the "navbar Form" in the menu, the width of the menu extends beyond the screen width in mobile mode (when resizing the browser window or viewing on a mobile device). Interesti ...

transmitting information using dataURL

Hey there! So I've got this code that does a neat little trick - it sends a dataURL to PHP and saves it on the server. In my JS: function addFormText(){ $('body').append('<input type="hidden" name="img_val" id="img_val" value="" /& ...

Retrieving user data using axios in React to fetch user_id information

I'm currently working on a React project where I have created a simple list and I am fetching data using axios. Here's a snippet of my code: https://codesandbox.io/s/old-worker-6k4s6 import React, { useState, useEffect } from "react"; ...

Having trouble connecting to MongoDB via a browser? It seems like you're attempting to access MongoDB using HTTP on the default driver port

Upon opening the terminal, I input the following commands: sudo mongod This results in the output: [initandlisten] waiting for connections on port 27017 Subsequently, I open another terminal and enter: sudo mongo As a result, the mongo shell is launc ...

I am experiencing issues with datejs not functioning properly on Chrome browser

I encountered an issue while trying to use datejs in Chrome as it doesn't seem to work properly. Is there a workaround for this problem if I still want to utilize this library? If not, can anyone recommend an excellent alternative date library that ...

Deactivate particular months within the JqueryUI date picker

I'm currently working on a booking form that involves the jQuery UI Datepicker. I've encountered a major issue that I could use some assistance with: There are certain trips where only specific days are available for booking, and these trips can ...

Can componentDidMount() capture errors thrown by promises or event handlers linked to a component?

Consider a scenario in React 16 where there is a component as shown below: class Profile extends React.Component { onClick = () => { throw new Error("Oh nooo!"); }); }; componentDidCatch(error, info) { alert(error) } render() ...

Step-by-step guide on integrating a custom JS file into an Angular component

Trying to grasp Angular, I embarked on adding some JavaScript logic to one of my components from a separate JS file. While following advice from a similar query (How to add custom js file to angular component like css file), it seems I missed something cru ...

Transforming HTML into a Console Experience (Angular 16)

I'm experimenting with creating a console/CLI style experience using HTML. The goal is to have the input fixed at the bottom of the window, while commands and output rise up from the bottom and eventually disappear off the top of the screen, enabling ...

Encountering a "MissingSchemaError" while attempting to populate the database with mongoose-seeder

I am facing an issue while trying to populate a database using mongoose-seeder. Despite setting up the schema correctly, I keep encountering a MissingSchemaError which has left me puzzled. Here is a snippet from the file where I define the schema: const m ...

Guide on removing the complete document in MongoDB with Node.js by utilizing the ObjectId

The objectID I'm working with is idd=60041d4312e61330c4b93b9b, and I tried using the following code: db.collection('users').remove({"_id":"ObjectId("+idd+")"}) Unfortunately, this approach isn't achieving the desired result. ...

Ways to transmit information from a React application to a Node server

As a Nodejs beginner, I am using the rtsp-relay library for live streaming. Currently, it is working in the frontend when the URL is included in the server proxy object like this: rtsp://.....@..../Stream/Channel/10. However, I want users to be able to inp ...

What is the best way to correct the mouse position in relation to the canvas parent?

I am currently working on incorporating the Vuejs Draw Canvas from this Codepen example into my project as a component. The functionality is all working well, but I've noticed that the mouse position seems to be relative to the window. This causes iss ...

Attempting to develop a server component that will transmit a JSON result set from a MySQL database located on the local server. What is the best method to send the server object (RowDataPacket) to the

After successfully rendering server-side pages and creating forms with react hooks for database updates, I encountered a challenge in integrating Ag-Grid into my application. Despite being able to retrieve data from the database using the mysql2 module and ...