XMLHttpRequest is unable to load due to preflight request access control check not being passed

Encountering an error in my Angular app while attempting to login locally (using Chrome):

XMLHttpRequest cannot load https://www.tickertags.com/app/api/login. 
Response to preflight request doesn't pass access control check: 
The 'Access-Control-Allow-Origin' header has a value 'http://localhost:8100'
that is not equal to the supplied origin.
Origin 'http://localhost' is therefore not allowed access.

The login function within my loginController:

function login(credentials) {
    console.log('credentials',credentials);
    AuthFactory.login(credentials).then(function (user) {
        $rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
        $scope.setCurrentUser(user);

        if (user.password_reset) {
            $location.path('/password');
        } else {
            $location.path('/tickers');
        }
    }, function () {
        console.log('"Invalid Username/Password"');
        $scope.loginData.message = "Invalid Username/Password";
        $rootScope.$broadcast(AUTH_EVENTS.loginFailed);
    }, function () {
        console.log('"Invalid Username/Password"');
        $scope.loginData.message = "Invalid Username/Password";
        $rootScope.$broadcast(AUTH_EVENTS.loginFailed);
    });
}

The AuthFactory.login function calls an API hosted on production. Unsure of what I might be overlooking. Here's the localhost link for reference: http://localhost/static/manage/v2/#/login

Answer №1

Sharing my solution in case it benefits others facing the same obstacle and struggling to reach server resources.

After some troubleshooting, I discovered the issue lied in attempting to access an absolute path with my API login call like: www.example.com/api/... rather than simply using /api/.... Making this adjustment resolved the problem.

Answer №2

To resolve the CORS issue, it is essential to configure both the front-end and back-end systems.

On the front-end side, you can handle default HTTP headers by invoking the myApp.run() method during initialization:

$http.defaults.useXDomain = true;
delete $http.defaults.headers.common['X-Requested-With'];

When it comes to the back-end, adjustments in request headers are necessary. While specifics may vary depending on your backend setup, I typically implement the following settings on my local Node server:

app.use(function (req, res, next) {
    res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
    res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
 });

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

Initiate ajaxForm submission again if necessary

Utilizing the ajaxForm function to transmit data to a PHP background process while some JavaScript functions monitor the asynchronous operation. In cases of failure, such as internet or electricity disruptions, I want users to have the ability to retry the ...

Submit function causes mutation in React form state

My current project involves learning React on my own and creating a small single-page React app using an Axios API. I'm facing a persistent issue with a POST request that keeps failing. After extensively using console.log, it appears that the form inp ...

Tips for adding multiple elements to the DOM at once

Is it possible to efficiently append elements to the DOM all at once? In the code snippet below, I am adding elements to a root element (tr_next) within a loop. $('.abc').each(function(){ //create element code here var tr_next = $("<tr> ...

What level of security is involved in sending an ajax request to a Codeigniter controller?

I am looking to securely pass the response of an ajax request to my codeigniter application. The current approach I have is as follows: Javascript var dataString = { 'id' : id }; var submit = $.ajax({ url:$('#hiddenurl').v ...

Reset form upon submission

When submitting a form and adding the contents to an array, I encounter an issue where the item added to the array remains linked to the form. How can I add the item to the array and then clear the form, similar to using jQuery's reset() function? Be ...

iOS device experiencing issues with Ionic 1 HTTPS service functionality

I recently entered the hybrid mobile development field, currently working with ionic1 and angularjs1. I am facing an issue where my service calls using the angularjs $http service in the controller work perfectly on android devices, but not on iOS devices. ...

Trouble with initializing the Ionic map controller

I have a mobile app with 5 tabs, one of which features a map. However, the map only loads when directly accessed through the URL bar. It seems that the controller is not loaded when navigating to the map tab through the app, as indicated by console logs. S ...

Extract the text content from an HTML file while ignoring the tags to get the substring

Hello, I am a newcomer to the world of Web Development. I have an HTML document that serves as my resume, formatted in HTML. For example: html <p>Mobile: 12345678891 E-mail: <a href="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Unconventional JavaScript Variable Declaration

While going through some source code, I stumbled upon this peculiar variable declaration that has me a bit confused. let eventsEnabled : ?boolean = null; Can someone explain what exactly this means? You can find the source code here. ...

Guide on positioning a 3D model to face forward in the direction of its movement

I'm just starting to learn about 3D graphics, so a lot of the terminology is unfamiliar to me... In my ThreeJs project, I have a 3D model flying around a room and avoiding walls. When it gets near a wall, it needs to turn slightly to avoid hitting it ...

The efficiency of XSL Template is significantly impacting loading time

Hello there, I am facing a challenge with my webpage's loading speed due to the code provided below. Can you assist me in optimizing it? <xsl:template match="Category" mode="CategorySelectorScript"> <xsl:variable name="ThisCateg ...

"Cross-Origin Resource Sharing (CORS) Configuration Issue Between FastAPI and Vue Deployed on Google Cloud

I am facing an issue with my FastAPI backend and Vue frontend setup where they are deployed separately. While they work fine on localhost when containerized and deployed on the same machine, I am having trouble with browser negotiation between the two in o ...

How can we ensure that an enum is accessible throughout the entire meanjs stack?

Currently, I am exploring the meanjs technology stack and facing a challenge in creating a centralized enum array that can be accessed throughout the project, from MongoDB to Angular. Can anyone suggest a smart solution for accomplishing this task? ...

Is it advisable to hold off until the document.onload event occurs?

I'm working with a basic HTML file where I need to generate SVGs based on data retrieved through an AJAX call. Do I need to ensure the document is fully loaded by enclosing my code within a document.onload = function() { ... } block, or can I assume ...

Experiencing difficulty retrieving individual :id information from a list in MEAN stack

**I'm experiencing issues retrieving a single :id from a list as the data returned is not what I expected... ** GET /article/5b0be8829f734a4e580a43c5 401 3.845 ms - 99 ===> response from my get request my api ===> var express = require ...

Utilizing Firebase authentication across various platforms

Exploring the best approach to incorporate multiple authentication providers with Firebase in a Next.js application. As of September 15, 2023, Firebase implemented email enumeration protection across all projects. If a user originally registered using em ...

The correct method to remove a specific attribute from the primary state in Redux that employs combineReducers - React Redux

I have been working on an app that requires authorization features such as registration, login, and logout. To achieve this, I am using redux. While the registration and login functionalities are operational, I encountered issues when attempting to delete ...

What is the best way to modify and execute js and css (less) files dynamically using ajax and jQuery?

Whenever I click a button, an ajax call is triggered to load various html code into a div with the id 'main'. While displaying the html content is not an issue, integrating and applying css and js code to my current page has proven to be challeng ...

Adjust the header as the user scrolls

Having a little issue with my header. I'm new to Bootstrap and would like to change my header when scrolling down. Everything works perfectly, but when I reload the page, the header remains in the "scrolling state". Apologies for any language mistakes ...

The year slider on d3 showcases the specific regions between each incremental step

I am working on creating a step slider in d3 (v5) that spans from the years 2000 to 2021 using the d3-simple-slider plugin. const slider = sliderBottom() .min(new Date(2000, 1, 1)) .max(new Date(2020, 1, 1)) .tickFormat(d3.timeFormat(& ...