2017-02-01 115 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(); 
});