Encountered an issue while attempting to deploy my app on Heroku: received the error message "The requested resource does not have the 'Access-Control-Allow-Origin' header"

Hi fellow developers, I'm currently facing an issue while trying to upload a simple app to my Herokuapp. Every time I attempt to log in or sign up and establish a connection with the back-end, I encounter the following CORS error:

"Access to fetch at '' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."

Both sign-in and sign-up attempts from the front end trigger this error. Upon seeing this, I tried adding an argument of some sort in the front-end header object, like so:

VUEX

const herokuUrl = "https://xxxxxxxxxxxxx.herokuapp.com/";

ACTION
     getUserSignedUp({ commit, dispatch }, payload) {
      // console.log(payload);

      fetch(herokuUrl + "mini/all_product/registering", {
        credentials: "include",
        headers: {
          "Content-Type": "application/json",
          "mode":"Access-Control-Allow-Origin",----------------------->PUT THIS HERE
        },
        method: "POST",
        body: JSON.stringify(payload),
      })
        .then((userData) => {
          // console.log("data sent :", JSON.stringify(userData));
          return userData.json();
        })
        .then((userData1) => {
          if (userData1.Error) {
            alert("fail on register", userData1);
            commit("setUserAuth", false);
          } else {
            alert("Success", userData1);
            dispatch("getUserLogIn", payload);
            commit("setUserAuth", true);
           }
        })
        .catch((error) => {
         alert("error", error);
        });
    },

However, this approach did not work as expected.

I'm also attaching my backend application's CORS configuration below:

package com.miniAmazon;

import com.fasterxml.jackson.annotation.JsonFormat;
...
...

@Configuration
@EnableWebSecurity
class WebSecurityConfiguration extends GlobalAuthenticationConfigurerAdapter {
...
}

@Configuration
@EnableWebSecurity
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
...
}

Any insights or advice on why this issue might be occurring? Thank you in advance for any help provided! Have a wonderful day!

Answer №1

The issue lies with the backend system, and it is necessary to configure CORS on your server. You can refer to the official spring website for detailed instructions:

Thank you for your attention, and I trust that this information will prove helpful.

Answer №2

For those looking to implement CORS within a WebSecurityConfigurerAdapter, here is a solution that worked for me:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf()
            .disable()
            .cors()
    //....
    ;
}

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setMaxAge(Long.MAX_VALUE);
    configuration.setAllowCredentials(true);
    configuration.addAllowedHeader("*");
    configuration.addAllowedOrigin("*");
    configuration.addAllowedMethod("*");

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);

    return source;
}

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

Instructions on utilizing type interfaces for prop drilling in my React Typescript counter

I am currently developing a basic counter app to monitor my progress in a digital card game that I enjoy playing. While attempting to pass props from the parent component to the child component, I encountered an issue where the props were not being success ...

Learn the steps to invoke a JavaScript function from a <td> element within an ng-repeat loop

How can I call an Angular function inside ng-repeat td and replace the value from the function with the value in the td element? The code snippet provided below is not functioning as expected. Instead of getting the date, the same getCSTDateTime function i ...

What is the process for establishing a connection between a websocket and an external API?

Currently, I have a route configured to fetch the weather data for a specific city using the openweathermap API Here is the code snippet from my index.js file: var express = require("express"), router = express.Router(); var weather = require("ope ...

Inject a value sent from response.render directly into the script tag

Below you will find a pug snippet. I am looking for a way to dynamically insert the user value into the chatConfig object. script. var chatConfig = { user : 'foo', pass : 'bar', } When rendering from my Express applicatio ...

The mysterious appearance of the <v-*> custom element in Vuetify Jest

Currently, I am in the process of writing unit tests for my project using Jest. The project itself is built on Vue, Vuetify (1.5), TypeScript, and vue-property-decorator. One particular area of focus for me has been creating a basic wrapper for the <v- ...

What might be causing AngularJS to fail to display values when using TypeScript?

I have designed the layout for my introduction page in a file called introduction.html. <div ng-controller="IntroductionCtrl"> <h1>{{hello}}</h1> <h2>{{title}}</h2> </div> The controller responsible for handling th ...

Is there a way to identify when no rows contain specific values in PostgreSQL or node.js and return false?

Here is an example of a table: P Q t f f t f f In SQL, is there a way to return false when querying for t t, but true when querying for t f, f t, or f f? Should this be handled with node.js by first doing a select and then using if-else statements based ...

Deleting validation messages from my MVC controls

I set up some validation in my Model by adding the following code: [Required] [StringLength(60, MinimumLength = 4)] [Display(Name = "Users code")] public string UserCode { get; set; } When c ...

Utilizing jQuery BBQ for Seamless Transitions – From Fading to Sliding and More

This is my first time posting a question here, even though I am an active user of stackoverflow. I have developed a website using jQuery BBQ to load pages through AJAX while still maintaining the ability to track history with the back button and other fun ...

The current status of an ASP.Net Mvc Ajax request

Currently, I am utilizing @Ajax.ActionLink to invoke a controller action in an ajax manner. Is there a method to identify if there is already an ongoing/pending ajax request on the page? The desired functionality is simple: when a user clicks the link, the ...

Displaying information according to the specified route prefix

Is there a method within VueRouter to identify if the route has a specific prefix? For instance, I have a navigation component that should display certain user-related links only if the route starts with /user-settings/ So, for example: /user-setti ...

Ordering tables in jQuery with both ascending and descending options

Trying to sort a table in ascending and descending order using jQuery? Here's the JavaScript code for it. However, encountering an error: Cannot read property 'localeCompare' of undefined If you can provide guidance on how to fix this so ...

Setting up the API URL for a Nuxt.js project running on localhost at port 8080: What you need to know

Within my vue file, I have specified that the base URL for my REST API is http://localhost:8080/api/. When accessing http://localhost:8080/api/dfc/system/docbases directly, the response returned is as follows: ["gr_swy","SubWayX_DEMO"] However, I am atte ...

IntelliJ automation in Java does not allow clicking the button

Currently, I am on the PayPal page and I need to automate clicking the agree button. <form id="ryiForm" class="proceed ng-pristine ng-valid" ng-class="{true: 'validated'}[validated]" ng-submit="confirm.$valid && onPay()" novalidate= ...

Limiting Ant Design Date range Picker to display just a single month

insert image description here According to the documentation, the date range picker is supposed to display two months on the calendar, but it's only showing one month. I carefully reviewed the documentation and made a change from storing a single va ...

Sloped Divider on the Upper Edge of the Page

I'm currently in the process of developing a new website, and I'm looking to create a unique design for the main navigation bar on the homepage. Here is the ideal layout that I have in mind: https://i.stack.imgur.com/pc8z4.png While I understan ...

Toggle the visibility of all elements using jQuery by creating multiple buttons for each action

I have a group of 4 buttons that control the visibility of images on the page. Each button toggles between showing and hiding all images when clicked. When a button is clicked, it changes its text from "HIDE ALL" to "DISPLAY ALL." The issue I'm facin ...

Transmitting FormData from Angular to a .NET MVC Controller

Here's my perspective: <form ng-submit="onFormSubmit()"> <div class="form-group"> <label for="Movie_Genre">Genre</label> @Html.DropDownListFor(m => m.Movie.GenreId, new SelectList(Model.Genres, "Id", "Na ...

Why isn't the AngularJS injected view resizing to fit the container?

As a novice delving into a project in the MEAN stack, I'm encountering inconsistent HTML previews. When I view it independently versus running it from the project, the display varies. Here's the intended appearance (in standalone preview): imgu ...

Eliminating the muted attribute does not result in the sound being restored

I am looking to implement a feature where a video loads automatically without sound, but when a user clicks a button labeled "Watch with Sound", the video restarts from the beginning and plays with sound. Below is the JavaScript code: let videoButton = do ...