2

我一直在尝试从关于这个主题的无数其他问题中尝试各种解决方案,但没有任何运气......

我正在尝试在 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 项目中:

应用程序.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。请求顺利通过。

如果有人能指出我正确的方向,我将不胜感激!

4

2 回答 2

1

Try add { 'Content-Type': 'application/x-www-form-urlencoded' } in your $http request like that

$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
})
于 2014-12-06T00:42:06.707 回答
-2

问题是 CORS 阻止了您的请求。您必须在具有相同端口的同一主机上提供服务和应用程序。为避免此问题,您可以使用代理将服务的 url “映射”到应用程序的 url。

干杯夜鹰

于 2014-08-26T07:04:20.437 回答