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