Unable to define headers within a request when using AngularJS

My application consists of two parts - an Angular frontend and a Rails server. Since they are on different domains, requests do not work by default. I have tried various solutions, including adjusting the stack, but nothing seems to work for me.

Below is the method in my Angular controller:

$scope.test =->
  # transform = (data) ->
  #   $.param data

  $http.post('http://localhost:3000/session/create', 'token=some',
    headers:
      'Access-Control-Allow-Origin': 'http://localhost:9000',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type, X-Requested-With'
    # transformRequest: transform
  ).success (responseData) ->
    console.log(responseData)

I have commented out the transform data function, but it did not affect the server response.

I have also configured my app as follows:

.config ["$httpProvider", ($httpProvider) ->
  $httpProvider.defaults.useXDomain = true
  delete $httpProvider.defaults.headers.common["X-Requested-With"]
]

I suspect this configuration may be causing the request to not behave like AJAX (though I'm not certain).

However, all my headers seem to be in one field

Access-Control-Request-Headers:access-control-allow-origin, accept, access-control-allow-headers, access-control-allow-methods, content-type
:

    Request URL:http://localhost:3000/session/create
    Request Method:OPTIONS
    Status Code:404 Not Found

    Request Headers

    Accept:*/*
    Accept-Encoding:gzip,deflate,sdch
    Accept-Language:en-US,en;q=0.8,ru;q=0.6
    Access-Control-Request-Headers:access-control-allow-origin, accept, access-control-allow-headers, access-control-allow-methods, content-type
    Access-Control-Request-Method:POST
    Connection:keep-alive
    DNT:1
    Host:localhost:3000
    Origin:http://localhost:9000
    Referer:http://localhost:9000/
    User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.8 Safari/537.36

    Response Headers

    Content-Length:12365
    Content-Type:text/html; charset=utf-8
    X-Request-Id:2cf4b37b-eb47-432a-ab30-b802b3e33218
    X-Runtime:0.030128

Chrome console shows:

OPTIONS http://localhost:3000/session/create 404 (Not Found) angular.js:6730
OPTIONS http://localhost:3000/session/create No 'Access-Control-Allow-Origin' header is     present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. angular.js:6730
XMLHttpRequest cannot load http://localhost:3000/session/create. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. localhost/:1

Other details:

class ApplicationController < ActionController::Base
  before_filter :allow_cross_domain_access

  protected

  def allow_cross_domain_access
    headers['Access-Control-Allow-Origin'] = '*'# http://localhost:9000
    headers['Access-Control-Allow-Headers'] = 'GET, POST, PUT, DELETE'
    headers['Access-Control-Allow-Methods'] = %w{Origin Accept Content-Type X-Requested-With X-CSRF-Token}.join(',')
    headers['Access-Control-Max-Age'] = '1728000'

  end
end

Routes are set with post "session/create". The session controller looks like this:

class SessionController < ApplicationController
  respond_to :json, :html, :js

  def create
    respond_with "logged in"
    # render nothing: true
  end
end

I am using the latest version of Angular 1.2.0.rc-2. You can find my project on GitHub here.

Answer №1

Your example has a mix-up in the request and response headers.

When attempting a cross domain request with CORS for anything other than a plain GET - such as a POST or including custom headers - the browser will initially send an OPTIONS request. This is evident in your developer console:

OPTIONS http://localhost:3000/session/create 404 (Not Found) angular.js:6730

The server should then include the appropriate headers in the response to the OPTIONS request.

Therefore, it's advisable to eliminate the custom headers from the Angular call. Additionally, ensure that your server/application properly responds to the OPTIONS request instead of returning a 404 error.

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

Content that is set to a fixed position within a hidden element will remain at the top

translate3d(0%, 0px, 0px); is causing issues with my position fixed element. In my demo, you'll notice that clicking the button should open up the content just fine, but it is supposed to stay fixed at the top in a position fixed. Therefore, when scr ...

Tips for creating $http calls in AngularJS

Having some issues with my code, as I'm unsure of the correct placement for making an $http request to a local server. api.js var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); va ...

Modifying the value of an animated status bar using the same class but different section

I need the status bars to work individually for each one. It would be great if the buttons also worked accordingly. I have been trying to access the value of "data-bar" without success (the script is able to process the "data-max"). However, the script see ...

What is the correct way to integrate the Ant Design library with Next.js for seamless server-side rendering?

I duplicated the official Next.js example using Ant Design at this link: https://github.com/vercel/next.js/tree/canary/examples/with-ant-design After cloning, I proceeded with npm install to install all dependencies. Then, I ran npm run dev to check if ev ...

Remove any javascript code from the ajax modal when it is closed or hidden

I am in the process of creating a music website that showcases songs along with their lyrics. One of the features I have added is a lyrics button that, when clicked while a song is playing, opens up a modal displaying the live lyrics. Everything works per ...

Is there something incorrect with the incrementation in JavaScript?

for (let i = 0; i < 5; ++i){ alert(i); } for (let i = 0; i < 5; i++){ alert(i); } Both of these constructs get the same result: 0, 1, 2, 3, 4. But what are the underlying differences between them? And does the choice of increment in a for l ...

Is it possible to log messages to the Selenium RC log using JavaScript in Selenium?

Seeking a way to log messages to Selenium RC's log using Javascript. For instance seleniumRc.log('Statement'); Wondering if it can be done? Appreciate any help! DashK ...

How can you display each input in a form sequentially?

My goal is to use jQuery to display each form text input one by one, allowing the user to enter data before moving on to the next input. Once the user has completed the entire form in segments, I want to submit all the responses at once. Is it possible to ...

Programmatically switch between show and hide using Angular Material

Is there a way to programmatically toggle between displaying and hiding attributes by clicking a button? For example, I have a card that includes both a map and a list view. Normally, these are shown side by side. However, on mobile devices, the list view& ...

Implementing advanced checkbox filtering feature in React

Does anyone have experience with creating dynamic Checkbox filtering in React using Material-UI? I'm finding it challenging because the checkbox options are generated dynamically from incoming data and need to be categorized by type of Select componen ...

Displaying Bootstrap alert after a successful jQuery AJAX call

I have been attempting to display an alert on a form once the submission action is completed. Here is my JavaScript function: function submitForm(){ // Initialize Variables With Form Content var nomeCompleto = $("#nomeCompleto").val(); v ...

Looking to showcase duplicate ranks that have been selected, and specifically identify which ranks are being duplicated using JavaScript/jQuery

In this section, we have implemented the logic to identify duplicate ranks. However, in addition to displaying which ranks are duplicated, I also aim to highlight the specific rank that is being duplicated within the range of 0 to 18. function validate( ...

Using Grails assets within AngularJS templates

Currently, I am developing a basic application using Grails 2.4.4 in combination with AngularJS 1.3.15. In order to integrate templates with Grails, I have incorporated the AngularJS Template Asset-Pipeline Plugin 2.0.7. Initially, my application did not ...

Have you ever wondered why the expression `Number(new Boolean(false))` always returns `0

In the case of Boolean(new Boolean(...)) === true, it is because new Boolean(...) is treated as an object. However, why does Number(new Boolean(false)) === 0 (+new Boolean(false) === 0) and Number(new Boolean(true)) === 1? Instead of resulting in NaN. Wh ...

What could be causing the href to malfunction on my local website?

I'm currently working on adding a new link that directs to a local HTML website within a menu list on a website. The main website is in ASPX format, but my focus is on the HTML version. The link I want to add leads to an HTML website stored on my loca ...

html - automatically populating input fields when the page loads

Currently, I have an HTML form embedded in the view and I am looking for a way to automatically populate specific input fields with json variables obtained from the server. Instead of manually writing JavaScript code for each field, my goal is to access th ...

Is there a way to identify the moment when a dynamically added element has finished loading?

Edit: I've included Handlebar template loading in my code now. I've been attempting to identify when an element that has been dynamically added (from a handlebars template) finishes loading, but unfortunately, the event doesn't seem to trig ...

Pass on only the necessary attributes to the component

I have a simple component that I want to include most, if not all, of the default HTML element props. My idea was to possibly extend React.HTMLAttributes<HTMLElement> and then spread them in the component's attributes. However, the props' ...

Making Asynchronous Requests in Rails

Is there anyone who can provide assistance with this issue? I've been attempting to make an AJAX request using Rails, but I keep encountering this error message: ActionView::Template::Error (Missing partial client_sub_folders/_client_sub_folder with ...

What is the method for specifying a .php page as the html source when using Ext.Panel?

I have a current situation where I manually set the html for an existing panel using a variable in the following way: var htmlContent = '<H1>My Html Page'; htmlContent += '[more html content]]'; var newPanel = new Ext.Panel({ ...