So I am trying to send a POST request with Content-Type: application/json from angular to my rails backend. I get the following error in console:
angular.js:12578 OPTIONS http://localhost:3000/api/student_create 404 (Not Found)
and
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.
Note the post request works properly when I use Content-Type: application/x-www-form-urlencoded
It also works in Postman with the application/json Content-Type set in the header.
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)
});
});
API controller (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
student.name= params[:name]
student.save
render json: "test".to_json #temporary
end
route: post 'api/student_create' => 'api#create_student'
Edit: frontend is on http://localhost:8008, backend is on localhost:3000
data
object in the angular controller) – Riyaz Shaikhdata
object – Riyaz Shaikh