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

Transfer information from the client to the server using AJAX and PHP by

When attempting to post a JavaScript variable called posY to a PHP file, an error occurred with the message: Notice: Undefined index: data in C:\xampp\htdocs\Heads_in_the_clouds\submitposY.php The posY variable is defined in the JavaSc ...

Design a model class containing two arrow functions stored in variables with a default value

I am looking to create a model class with two variables (label and key) that store functions. Each function should take data as an input object. If no specific functions are specified, default functions should be used. The default label function will retur ...

Exploring Improved Error Handling for Spring MVC REST Service and Client. Seeking more efficient solutions for managing errors

Seeking Improved Error Handling for Spring MVC REST Service and Client I am interested in enhancing the way errors are handled in my Spring MVC REST Service and Client. Sometimes I need to send an error message or a status code back to the client, but I a ...

How can I invoke a PHP script using AJAX?

I am currently working on implementing a feature that involves multiple tables where users can move table rows between the tables. I want to use ajax to call a php script that will update the database with the new values, specifically assigning a new paren ...

The initial value set for the innerHTML property of a div element

I have a requirement in my application where I need to confirm if the container div is empty before adding specific text elements to it. The innerHTML of this div is frequently created and removed within the app, so it's crucial to validate its emptin ...

Challenges faced when dealing with MongoDB and the latest version of webpack

Struggling to navigate MongoDB and React.js, encountering issues with MongoDB dependencies. Here are the dependencies listed in package.json: "dependencies": { "dotenv": "^16.3.1", "mongodb": "^4.1.0", &qu ...

Does the use of 'window.location.replace' in Chrome cause a session to be destroyed in PHP when redirecting to a specified page?

Apologies if the question seems a bit convoluted, but let me explain the scenario. Here is an example of an Ajax function I am working with: $.ajax({ url:"../controllers/xx_register.php", type:"POST", data:send, success: function(resp ...

Retrieve tabs according to the value selected in the dropdown menu

When a value is selected from a dropdown with options 1 to 5, I want to display a corresponding number of tabs. Below is the HTML code for the select box: <select id="Week" name="Week"> <option value="1">1</option> <option val ...

What is the best way to select the element where a user has clicked using JavaScript?

Referencing a previous question on Stack Overflow, the goal is to track user clicks in a Firefox browser using JavaScript. The provided JavaScript code almost achieves this: var DocElements = document.getElementsByTagName('*');for(var i = 0; i & ...

Looking for assistance with deleting a child element in an XML file using PHP

I need help figuring out how to delete a child from my jobs.xml file with a PHP script. My jobs.xml file looks like this: <jobs> <event jobid="1"> <title>jobtitle</title> <desc>description</desc> &l ...

Patience is key when it comes to waiting for a function to finish before moving on to the next step

I'm delving into the world of node js and currently immersing myself in the concepts of promises and async/await. Here's a code snippet I've been experimenting with, but I can't quite figure out how to ensure that the code waits until t ...

Refining to Showcase One Menu Selection

I am having an issue with my bootstrap menu that includes a search field. The problem is that when I try to filter the dropdown menu using the search field, it filters all dropdown items instead of just the one I want. For example, if I search for a term f ...

Animating jQuery Accordion in Horizontal Direction Extending to the Far Right

After implementing a horizontal accordion in jQuery based on the tutorial found at the following link: A minor issue arose during animation where a slight space was added on the far right side, causing the tabs to shift slightly. This problem is particula ...

Using jQuery, is it possible to retrieve the product name and image dynamically?

I'm currently working on implementing an add to cart functionality using jQuery. When the add to cart button is clicked, the product name and image should be displayed. I can achieve this statically but I need help figuring out how to dynamically retr ...

Parse the JSON string into a list of C# objects when the string is received as NULL in the request

I'm currently working on a code snippet that converts a JSON string into a list of objects: public class rest_all { public string restaurants { get; set; } } public class rest_all_data { ...

Adjusting firebugx.js for compatibility with Internet Explorer Developer Tools

The firebugx.js file (viewable at http://getfirebug.com/firebug/firebugx.js) is designed to detect the installation of Firebug by checking both !window.console and !console.firebug. However, this method does not account for the native console object in the ...

Using Node and Mongoose to link documents that rely on each other for reference

Is there a way to add a document after another document has been successfully inserted using node and mongoose? For example, I initiate the creation of a document with mongoose, and once it is successfully added, I want to trigger the insertion of another ...

The React application is functioning properly; however, during compilation, it continually displays an error stating that the module cannot be found

Compilation Failed. Error: Module not found, unable to resolve the specified path. webpack compiled with 1 error I was hoping for a successful compilation, but unfortunately encountered an error. It's perplexing as the application is functioning co ...

Exploring Angular14: A guide to efficiently looping through the controls of strictly typed FormGroups

Currently, I am working on upgrading my formGroups to be strictly typed in Angular v14. Within my FormGroup, there is a specific block of logic that iterates through all the controls and performs an action (this part is not crucial as I am facing issues be ...

Investigating a bug in compiling D3 directives within AngularJS testing

I am encountering an issue with my angularjs directive that contains D3 code. Everything works perfectly when used in the application, but when I compile it for testing purposes, some of the D3 code is generated twice - specifically, the nodes and paths. ...