Angular is unable to POST to Rails server with the content-type set as application/json

Currently, I am attempting to send a POST request with Content-Type: application/json from Angular to my Rails backend. However, an error is being displayed in the console:

angular.js:12578 OPTIONS http://localhost:3000/api/student_create 404 (Not Found)

In addition, I am seeing:

XMLHttpRequest cannot load http://localhost:3000/api/student_create. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8008' is therefore not allowed access. The response had HTTP status code 404.

I have observed that the post request functions correctly when using

Content-Type: application/x-www-form-urlencoded
.

Furthermore, it also works in Postman when setting the application/json Content-Type in the header.

Here are the sections related to the Angular Controller:

.controller('View1Ctrl', function($scope, $http) {

  var data = {
    name: "name"
  };
  $http({
    url: 'http://localhost:3000/api/student_create',
    dataType: 'json',
    method: 'POST',
    data:data,
    headers: {
      "Accept": "application/json",
      "Content-Type": "application/json",
      "Access-Control-Allow-Origin": "*"
    }
  }).then(function(response) {
    console.log(response)
  }, function(error) {
    console.log(error)
  });

});

The following segment relates to the API controller in Rails:

class ApiController < ApplicationController
     before_action :set_headers
     skip_before_action :verify_authenticity_token

  def set_headers
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT'
    headers['Access-Control-Request-Method'] = '*'
    headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
    end
  def create_student
    student = StudentUser.new
    ...
    render json: "test".to_json #temporary
  end

Route:

post 'api/student_create' => 'api#create_student'

Note: the frontend is hosted at http://localhost:8008, while the backend is on localhost:3000

Answer №1

Dealing with the issue of cross-origin resource sharing while integrating Rails with Angular can be a challenge. However, I encountered this problem as well and managed to find a solution through the 'rack-cors' gem. You can refer to its documentation here. By default, Rails does not support cross-origin requests but implementing this gem can handle such requests effectively.

Here are the steps you can follow:

First, install the gem:

gem install rack-cors

Alternatively, add it to your Gemfile:

gem 'rack-cors', :require => 'rack/cors'

Next, in your application.rb file:

module YourApp
  class Application < Rails::Application

    # ...

    # For Rails 3/4

    config.middleware.insert_before 0, "Rack::Cors" do
      allow do
        origins '*'
        resource '*', :headers => :any, :methods => [:get, :post, :options]
      end
    end

    # For Rails 5

    config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins '*'
        resource '*', :headers => :any, :methods => [:get, :post, :options]
      end
    end

  end
end

Answer №2

For a solution, check out the resource from How to Set Up CORS Headers in Your Rails API

Even if your client is on “localhost:3000” and your server is on “localhost:3001”, the response will be ignored unless your web service establishes a permissive CORS policy. This policy is determined by the server setting specific CORS headers in the HTTP response that the client app (such as a browser) must adhere to. Here's an example of configuring these headers:

# in config/application.rb
config.action_dispatch.default_headers = {
  'Access-Control-Allow-Origin' => 'http://my-consumer-site.com',
  'Access-Control-Request-Method' => %w{
    GET POST OPTIONS
  }.join(",")
}

Note:

It's important to avoid using 'Access-Control-Allow-Origin' => '*' unless you are offering a public API meant for any consumer to access.

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

What is the best way to invoke a controller function from within a directive's link function using '&' and passing a parameter?

Trying to pass a parameter into a function within a directive link function has been a bit challenging. I've come across questions and examples like this one on Stack Overflow, as well as blog posts such as What IBroke. While I've seen paramete ...

Is there a way to add a fade-in and slide-in effect to this dropdown JavaScript, as well as a fade-out and

Although I lack the necessary knowledge of Javascript, I am aware that my request may be a bit much. The code I currently have is directly from the w3school dropdown-list demo. Would it be possible for you to help me implement a fade in and slide in effect ...

Revise the reply within ExpressJS

I need help with editing the response to a request in Express. When the request is made via XHR, I want to encapsulate the body inside a JavaScript object. This way, different parts of the page can be accessed individually within the JavaScript object, suc ...

Developing an ASP application using the MVP pattern to return JSON data can be transformed into a S

I’m looking to incorporate the following code into a sails js Controller public JsonResult GetEvents() { //Using MyDatabaseEntities as our entity datacontext (refer to Step 4) using (MyDatabaseEntities dc = new MyDatabaseEntities()) { ...

Aligning dynamically-sized TextInput in React Native

I am facing a challenge in centering a text input with a width that matches the length of the input text. I have tried using alignSelf: 'center' and alignItems: 'center', but the text input is not visible without specifying a width. Fo ...

Generating a dynamic SQL Insert statement based on an array object

I am currently working on a Typescript project where I am looking to optimize my Insert function by creating one Insert statement for all the elements in an object, rather than generating multiple Inserts for each array item. Here is the code snippet of m ...

Removing characters from a string with regular expressions

I need to eliminate instances of << any words #_ from the given text. stringVal = "<<Start words#_ I <<love#_ kind <<man>>, <<john#_ <<kind man>> is really <<great>> <<end words#_ "; The d ...

How can you use JavaScript to create a JSON object using values from an HTML form textarea and then send

I need to create an HTML form that will send specific information in the Http-request body. { “info” : { “id” : “123” “text1” : <data from html text-box> } Therefore, my goal is to convert the provided data into a JavaScri ...

Track and manage date ranges inclusive of specific times

http://jsfiddle.net/7vzapm49/1/ var startdatearr = [new Date("04 Dec 2014 14:30:00").toUTCString(), new Date("07 Dec 2014 14:30:00").toUTCString()]; var enddatearr = [new Date("05 Dec 2014 14:30:00").toUTCString(), new Date("08 Dec 2014 14:30:00").toUTCSt ...

Is there a way for me to properly initiate the Material UI Modal from the parent component?

This is the main component: import React from 'react'; import ChildModal from 'ChildModal'; const MainComponent = () => ( <div> <span>Click </span> <a>HERE TO OPEN MODAL</a> <div> ); ...

Tips for retrieving the ID of a dynamic page

In my Higher Order Component (HOC), I have set up a function that redirects the user to the login page if there is no token. My goal is to store the URL that the user intended to visit before being redirected and then push them back to that page. However, ...

Trouble selecting options in hierarchical data

I've been attempting to run this sample code for selecting an option from a select element with hierarchical data, but it seems to be having some issues. $scope.options = [ { id: 1, info: { label: "Item 1" } }, { id: 2, info: { label: ...

Avoiding leaps through the use of dynamic pictures?

Currently, I am implementing the picture element along with srcset to download the same image but in varying resolutions depending on the screen size of the device. The image has a style of max-width: 100%, causing it to shift the content below when downl ...

Selective Circle Appending Techniques

I am having some issues with my bubble chart code. The data file I am working with contains instances where the GDPperCapita and/or LifeExpectancy values are either 0 or NaN, causing problems when appending circles to the chart. I would like to know if th ...

What steps can be taken to resolve the error involving the preflight request failing to pass the access control check?

I'm currently working with angular code in one VM and node code in another. I am trying to make an API call from the angular VM to the node VM, and I have already included the cors module. However, when making the API call, I keep encountering the fol ...

Tips for fetching data from a Django REST API endpoint and displaying it in a Flutter Dropdown widget

I am currently working on a project that involves using Django REST for the backend with Flutter dropdown widget to display a list of Country states. However, I am facing challenges in getting the list of states to appear in the dropdown menu. Can anyone p ...

Creating a copy-paste functionality in my table by utilizing an Angularjs directive

I am currently working on a table where I need to enable the ability to copy data from one cell and paste it into another. I understand that I will need to utilize an event listener like element.on('ctrl-c',function(e){ $scope.textToBeCopied = ...

Utilize AngularJS to convert datetime into decimal format

Can you help me understand how to convert a decimal number to a date in AngularJS? Here's an example: Source: 20150911141804 Expected Format: 2015-09-11 I'm trying to format this source number within a cellTemplate in ui-grid. Thank you! ...

A step-by-step guide to displaying API data in a React frontend using functional components

I've managed to create a backend API using Node+Express+MSSQL and tested the routes with POSTMAN. However, I'm facing challenges when trying to display the data on the front-end using React Functional components/hooks. I'm unsure if I'm ...

Search for text in multiple tables using jQuery and automatically trigger a button click event when the text is found

I am attempting to query certain tables and click a button within a cell of a specific table. Below is the code I am currently using: links[1].click(); iimPlayCode('WAIT SECONDS = 2') var compTabs = window.content.document.getElementById(' ...