我一直在尝试各种关于这个主题的其他问题的解决方案,没有任何运气......
我正在尝试设置一个rails-api项目,在AngularJs中有一个前端 . 他们将在不同的领域 . 我可以毫无问题地发出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 . 请求没有问题 .
如果有人能指出我正确的方向,我真的很感激!
2 回答
尝试在$ http请求中添加{'Content-Type':'application / x-www-form-urlencoded'}
问题是CORS阻止了您的请求 . 您必须在同一主机上使用相同的端口提供服务和应用程序 . 为避免此问题,您可以使用代理将服务的URL“映射”到应用程序的URL .
干杯夜鹰