所以我試圖發送POST請求與Content-Type:application/json從angular到我的rails後端。我收到以下錯誤控制檯:無法使用內容類型:應用程序/ json從angular到rails
angular.js:12578個選項http://localhost:3000/api/student_create 404(未找到)
和
的XMLHttpRequest無法加載http://localhost:3000/api/student_create。對預檢請求的響應不會通過訪問控制檢查:請求的資源上不存在「訪問控制 - 允許來源」標頭。因此不允許訪問原產地'http://localhost:8008'。響應有HTTP狀態代碼404
注發佈請求正常工作,當我使用Content-Type: application/x-www-form-urlencoded
它也適用於郵差與應用/ JSON在Content-Type頭中設置。
角控制器:
.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控制器(導軌):
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
路線:post 'api/student_create' => 'api#create_student'
編輯:前端是http://localhost:8008,後端是在localhost:3000
什麼是數據的大小你正在試圖發佈? – alphapilgrim
這只是文字。 (在'data'在相位控制器對象) –
您可以驗證您的發送對象是有效的JSON對象 – alphapilgrim