2014-03-12 34 views
18

HTTP這是我的代碼:錯誤消息'XMLHttpRequest無法加載。跨起源請求僅支持在AngularJS」

MyAppModule.factory('EventData', function($http,$log){ 
    return { 
     getEvent : function(successcb){ 

      $http({method: 'GET', url: './js/Services/products.json'}). 

      success(function(data) { 
       $log.info("success"); 
      }). 
      error(function(data) { 
       $log.info("error"); 
      }); 
     } 
    }; 
}); 

我有一個本地位置的簡單JSON文件,我想使用的AngularJShttp方法來讀取它。我收到以下錯誤:

XMLHttpRequest cannot load file:///C:/Users/Avraam/Documents/GitHub/AngularJS/app/js/Services/products.json Cross origin requests are only supported for HTTP. angular.min.js:73 Error: A network error occurred.

我的錯誤是什麼?我沒有使用任何服務器;我只是用Chrome打開我的索引文件。這是錯誤嗎?如果我想使用http方法,我應該使用服務器嗎?

+5

是的,你應該設置一個HTTP服務器應用程序來承載頁面和JSON。 Ajax通常不允許使用'file://'。 –

+4

如果您使用的是Python,可以通過從包含index.html的目錄運行'python -m SimpleHTTPServer'來啓動服務器。這些頁面可以在127.0.0.1:8000訪問,並且不會限制本地頁面。否則,XAMPP或WAMP無論如何都是。 – skjoshi

回答

22

如果這是地方發展和您使用的是Chrome,你需要一對夫婦的參數運行的Chrome放鬆安全這樣的:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files --disable-web-security 
+1

如果你在Mac上運行? – mtmurdock

+1

@mtmurdock使用Safari。它會工作! – WaaleedKhan

+0

這並不理想,因爲我的工作不支持Safari,Chrome是。 – mtmurdock

5

對於Mac用戶相應的命令是:

open /Applications/Google\ Chrome.app --args --allow-file-access-from-files --disable-web-security 
+0

使用--disable-web-security標誌導致Chrome給我一些不支持的標誌錯誤。我刪除它,它的工作。 –

14

我運行我的網頁關閉服務器修復了這個問題,像這樣

cd /path/to/dir/with/the/index/file 
python3 -m http.server 

然後在瀏覽器


,或者如果你的電腦還沒有安裝Python 3

python -m SimpleHTTPServer 

打開http://localhost:8000詳情請參閱this answer

+0

您可以通過使用實時服務器來增強此工作流程,因爲您在編輯和保存頁面時,會自動使用更改來刷新頁面。 https://github.com/tapio/live-server – Dan

-1

您可以使用WAMP或其他Web開發平臺創建虛擬主機。

我沒有問題。

0

以下命令適用於我。但命令之前,你需要無論如何停止鍍鉻工藝,可從任務管理器

 "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files --disable-web-security --disable-web-security 

3

如果您在Windows環境是,和使用的包管理NPM最簡單的就是安裝HTTP服務器全球:

npm install -g http-server

然後只需運行HTTP服務器在您的任何項目目錄:

Eg. d:\my_project> http-server

Starting up http-server, serving ./ Available on: http:169.254.116.232:8080 http:192.168.88.1:8080 http:192.168.0.7:8080 http:127.0.0.1:8080 Hit CTRL-C to stop the server

容易,一不小心讓您的瀏覽器中打開容易存在安全隱患。

+0

你是男人:) – Fadeel

-1

運行一個http節點服務器並提供該文件。

  1. 安裝連接,並服務於靜態與NPM

    $ NPM安裝連接服務靜電

  2. 與此內容創建server.js文件:

    VAR連接=需要(」 '連接);var serveStatic = require('serve-static');connect()。use(serveStatic(__ dirname))。listen(8080,function(){ console.log('Server running on 8080'); });

  3. 與Node.js的

    運行

    $節點server.js

現在你可以去該文件是由會做跨域請求沒有任何錯誤:http://localhost:8080/yourfile.html

相關問題