[英]CORS in rails-api and angularJs
我一直在嘗試關於該主題的無數其他問題的各種解決方案,但是沒有任何運氣...
我正在嘗試使用AngularJs中的前端設置一個rails-api項目。 它們將位於不同的域中。 我可以毫無問題地發出GET請求。 但是當我嘗試執行PUT時,我進入了Chrome控制台:
XMLHttpRequest cannot load http://0.0.0.0:3000/thingies/1.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:9000' is therefore not allowed access
這是我失敗的請求的樣子:
Remote Address:0.0.0.0:3000
Request URL:http://0.0.0.0:3000/thingies/1
Request Method:OPTIONS
Status Code:404 Not Found
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,ja;q=0.6,ko;q=0.4,pt;q=0.2,ro;q=0.2,zh-CN;q=0.2
Access-Control-Request-Headers:accept, content-type
Access-Control-Request-Method:PUT
Cache-Control:no-cache
Connection:keep-alive
Host:0.0.0.0:3000
Origin:http://localhost:9000
Pragma:no-cache
Referer:http://localhost:9000/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36
Response Headersview source
Connection:Keep-Alive
Content-Length:17164
Content-Type:text/html; charset=utf-8
Date:Tue, 26 Aug 2014 06:48:06 GMT
Server:WEBrick/1.3.1 (Ruby/2.1.1/2014-02-24)
X-Request-Id:xxxxxx-xxxxxxx-xxxxxx-xxxxxxxxxx
X-Runtime:0.027031
這是我在AngularJs中的app.js:
angular
.module('myApp', [
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'restangular',
])
.config(function ($routeProvider,RestangularProvider, $httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common["X-Requested-With"];
$httpProvider.defaults.headers.common["Accept"] = "application/json";
$httpProvider.defaults.headers.common["Content-Type"] = "application/json";
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'HomeCtrl'
.otherwise({
redirectTo: '/'
});
RestangularProvider.setBaseUrl('http://0.0.0.0:3000');
});
這是在我的Rails項目中:
application.rb:
class Application < Rails::Application
config.action_dispatch.default_headers.merge!({
'Access-Control-Allow-Origin' => '*',
'Access-Control-Request-Method' => '*'
})
end
我的routes.rb,application_controller.rb和thingy_controller是默認的腳手架文件。 (我嘗試根據CORS的其他解決方案修改它們,沒有任何運氣。)
我也使用了POSTMAN(Chrome擴展程序),以查看是否可以使用PUT。 請求順利通過。
如果有人可以為此指出我正確的方向,我將不勝感激!
嘗試像這樣在您的$ http請求中添加{'Content-Type':'application / x-www-form-urlencoded'}
$http({
method : 'POST',
url : 'backend.json',
data : $.param($scope.yourFormData), // pass in data as string, important!
headers: { 'Content-Type': 'application/x-www-form-urlencoded' } // set the appropriate headers
})
問題在於,CORS阻止了您的請求。 您必須在具有相同端口的同一主機上提供服務和應用程序。 為避免此問題,您可以使用代理將服務的URL“映射”到您的應用程序的URL。
干杯夜鷹
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.