2017-02-01 113 views
0

当我尝试使用POSTMAN和配置授权参数(kermit:kermit)发送GET请求到Activiti REST URL时,它的作用就像一个魅力。Activiti REST在GET请求后返回401

但是,当我试图做同样的事情,只有角$ http服务,它将返回以下错误:

XMLHttpRequest cannot load http://localhost:8080/activiti-rest/service/repository/deployments . 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:8081 ' is therefore not allowed access. The response had HTTP status code 401.

这里是我的控制器:

(function() { 
'use strict'; 

angular 
    .module('doktorat-app-test') 
    .controller('TestController', TestController); 

TestController.$inject = ['$http', '$base64']; 
function TestController($http, $base64) { 
    var tcr = this; 
    $http.defaults.headers.common['Authorization'] = 'Basic ' + $base64.encode('kermit:kermit'); 


    tcr.text = 'ssdsds'; 


    $http.get('http://localhost:8080/activiti-rest/service/repository/deployments') 
    .then(function(response){ 
     tcr.text = response.data; 
    }); 
} 

})(); 

有没有人遇到了类似的错误? 花了超过2天试图解决此问题,但没有任何成功。

P.S.我正在使用NodeJS http-server来运行我的Angular App,它运行在8081端口上。

+0

https://stackoverflow.com/search?q=No+Access-Control-Allow-Origin+header+is +现在+ + +请求+资源 – sideshowbarker

回答

0

由于您试图访问http://localhost:8081/上的rest api,因此从​​开始,浏览器将检查您的服务器是否使用预检请求来执行CORS。你可以得到约CORS细节下面网址:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

在一个服务器托管的应用程序通常不会被允许访问其他sever.This限制托管的资源是由所有最重要的,现在的浏览器是一个天实施。

为了使其工作,您的其余api服务器必须告诉其他一些服务器也将被允许呼叫。为此,您需要在您的rest api服务器中实现CORS文件管理器。

既然你没有说明具体的langauge您使用的是休息,我为JAVA提供一个开源CORS过滤库:

http://software.dzhuvinov.com/cors-filter.html

其解决您的问题。

+0

感谢您的评论,它给了我一个想法如何解决我的问题。 由于activiti REST运行在localhost:8080 Tomcat及其webapps文件夹中,我还将我的角度应用程序存储在webapps文件夹中并解决了我的问题。这不是一个优雅的解决方案,但在我的情况下,我只需要它的工作。干杯。 – Martel

0

为了让CORS特定域,您可以使用中间件如下:

app.use(function(req, res, next) { 
    res.header("Access-Control-Allow-Origin", "http://localhost:8081"); 
    res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); 
    res.header("Access-Control-Allow-Credentials", "true"); 
    res.header("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization, X-Requested-With"); 
    next(); 
});