When attempting to log in with Facebook using Angular, the requested resource does not have the necessary 'Access-Control-Allow-Origin' header

Having difficulty with integrating Facebook login through Angular.js in my Rails App.

<li><a ng-click="fb_login()" href="">Login with Facebook</a></li>

In the UserCtrl:

$scope.fb_login = function() {
  user.social_media_login();
}

This triggers a function on the user.js service:

social_media_login: function() {
  return user.submit({method: 'POST', 
                      url: '../users/auth/facebook', 
                      success_message: "You have been logged in."
                    });
}

I've set up the rack-cors gem on the backend, and also included this code in my application_controller.rb:

before_filter :cors_preflight_check
before_filter :cors_set_access_control_headers

def cors_set_access_control_headers
  headers['Access-Control-Allow-Origin'] = '*'
  headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
  headers['Access-Control-Request-Method'] = '*'
  headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
end

def cors_preflight_check
  if request.method == :options
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
    headers['Access-Control-Allow-Headers'] = '*'
    headers['Access-Control-Max-Age'] = '1728000'
    render :text => '', :content_type => 'text/plain'
  end
end

However, I'm encountering an error in Chrome console:

XMLHttpRequest cannot load https://www.facebook.com/dialog/oauth?client_id=xxx&redirect_ur…pe=code&scope=email&state=yyyy. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

The terminal output of my app displays:

Started POST "/users/auth/facebook" for ::1 at 2015-09-07 20:07:35 +0100
I, [2015-09-07T20:07:35.847058 #18719]  INFO -- omniauth: (facebook) Request phase initiated.

Answer №1

After reading a blog post, I was inspired to tweak my angular.js logic to get it working.

In the UserCtrl, I made changes to the fb_login() function like this:

$scope.fb_login = function() {
  var openUrl = '/users/auth/facebook?client_id=' + 487506314749953;
  window.$windowScope = $scope;
  window.open(openUrl, "Authenticate Account", "width=500, height=500")
}

This code opens a new tab for entering Facebook credentials. In the MainCtrl, which controls the entire angular app scope, I added this:

if(window.opener ) {
  window.opener.location.reload(true);
  window.close()
  window.location.reload();
}

The intention is to close the tab after logging in through Facebook and refresh the original tab to reflect the app's updated state (e.g., different navbar options).

In the backend callback controller, setting a cookie for the current user is essential:

def facebook
  @user = User.from_omniauth(request.env["omniauth.auth"]) if request.env["omniauth.auth"].present?

  if @user && @user.persisted?
    sign_in @user
    cookies[:uId] = request.env["omniauth.auth"]["uid"]
  else
    session["devise.facebook_data"] = request.env["omniauth.auth"]
  end
  redirect_to root_url
end

On the angular side, retrieving the cookie ensures everything works seamlessly.

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

When trying to reach the state link in a different component, it leads to a typerror indicating that the state is undefined

I'm trying to pass state down using the <Link> component to the NextPage component like this: <Link to={{pathname: `/job-run-id/${item.job_run_id}`, state: { prevPath: location.pathname }}} > {item.job_run_id} </Link> The NextPage c ...

Having trouble accessing `event.target.value` when selecting an item from the autocomplete feature in Material-UI with the

*** UPDATED CODE BASED ON RECOMMENDATIONS *** I am currently in the process of familiarizing myself with material-ui. I have been exploring how to incorporate event handling with material-ui components, specifically by combining an autocomplete feature wit ...

Utilizing a Custom Validator to Compare Two Values in a Dynamic FormArray in Angular 7

Within the "additionalForm" group, there is a formArray named "validations" that dynamically binds values to the validtionsField array. The validtionsField array contains three objects with two values that need to be compared: Min-length and Max-Length. F ...

When using PHP to echo buttons, only the value of the last echoed button will be returned in JavaScript

I am encountering an issue when trying to define a dynamic var for button value in my JavaScript code. Despite it working in PHP, the same code does not seem to function properly in JavaScript. Imagine I have three buttons echoed using PHP with values 1, ...

Implementing a password prompt in CodeIgniter using JavaScript

I need to delete a teacher as an admin, but before doing so, I want to require them to re-enter their password. However, I'm having trouble getting the delete function to work even though the prompt is displayed. Can someone help me figure out what I& ...

The patch method is failing to upload using axios

In my project using Laravel 5.8 and Vue.js 2, I have encountered a problem with the .vue file: let formData = new FormData(); formData.append('name', this.name); formData.append('image',this.image) formData.a ...

A guide on effectively employing the indexOf method within an array set in AngularJS

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <script> var app = angular.module('myApp', []); app.controller('myctrl', function($scope) { $scope.state = [{name:'T ...

Troubleshooting Problem with CSS Background-Image in Safari

These questions have been popping up all over the web with little response. I've added some CSS in jQuery like this: $('#object').css('background-image', 'url(../../Content/Images/green-tick.png)'); This works in all b ...

What is the best method to showcase weekly attendance in a Rails application for a specific month?

I have a requirement for displaying attendance based on selected month and year. The interface should include two drop-down menus - one for selecting the month, another for the year, as well as a submit button. Initially, upon choosing a month, I want to d ...

Combining Rails 3.1 authenticity tokens with the uploadify feature

Currently, I am facing an issue while trying to integrate Uploadify with my Rails 3.1 application. Despite setting up all the necessary steps such as middleware, initializers, and configuration, everything seems to be working correctly except for one parti ...

unique html jquery custom binding

I have a task that involves achieving the following... This is what my HTML would look like <div id="targetdiv"> <div class="Comments30" title="{@something1}"></div> <div class="{@something2}" title="{@something3}"></div> &l ...

Adapt the stylesheet for mobile devices using CSS

I am struggling with updating file paths in CSS depending on whether the end user is accessing my site from a PC or mobile device. Below is my CSS code, where I attempted to redirect users if they are on a handheld device: <link rel="stylesheet" type=" ...

Could this be considered normal protocol when uploading a picture to a user's wall using the Facebook SDK on iOS?

While using the code below to post on the user's wall, I noticed that it created a photo album with my app's name and added the image there too. Is this normal behavior for an iOS app? Can I post to the wall without saving the image in the user&a ...

An Ajax request redirects to a PHP file instead of invoking a different PHP file

After submitting my form with the class .login, an ajax call is triggered to login.php. Inside login.php, there is a call to welcome.php to verify the encrypted password and check if the user name exists in the database. Although the ajax call is successfu ...

Retrieve information from a JSON file according to the provided input

Can someone help me fetch data based on user input in JavaScript? When the input is 'Royal Python', I'm supposed to retrieve details about it. However, the code provided gives an error stating 'The file you asked for does not exist&apo ...

Jumping through pages using a For Loop in Angular 5

Angular 5 - Chrome. Seeking advice on preventing page jumping. I have a table connected to an ngFor loop. When I am at the top of my page and trigger an action that adds an element to the array, if that table with the ngFor loop is off-screen at the time ...

Disable the meta tags in Zurb Foundation 5

I have searched extensively online but haven't been able to find a solution for this issue. How can I disable these zurb foundation 5 meta tags in the <head>: <meta class="foundation-mq-small"> <meta class="foundation-mq-small-only"> ...

Seeking information on determining the actions performed when DOMContentLoaded is triggered in JavaScript?

Interested in obtaining all the code that is triggered when DOMContentLoaded event is fired or jQuery's $(document).ready() function? I am looking to improve my website's performance, and after running a speed test, I discovered that 2 seconds o ...

Troubleshooting an issue with Laravel's Bootstrap 5.2 dropdown functionality

After setting up a pre-configured navbar from the Bootstrap website, I noticed that the dropdown feature is not working. This issue arose with the latest version of Bootstrap 5.2 which was integrated into my Laravel project without any modifications to the ...

Extracting information from an external website in the form of XML data

Trying to retrieve data from an XML feed on a remote website , I encountered issues parsing the XML content and kept receiving errors. Surprisingly, fetching JSON data from the same source at worked perfectly. The code snippet used for XML parsing is as f ...