2017-07-19 63 views
0

我正在使用angular-cli,我正在通過發送XMLHttpRequest使用單擊事件來讀取txt文件並得到此錯誤。請求僅支持協議方案:http,數據,鉻,鉻擴展,https

XMLHttpRequest cannot load file:///E:/xampp/Angular- 
]cli/Login/src/app/employees.txt. Cross origin requests are only supported for 
protocol schemes: http, data, chrome, chrome-extension, https. 

這是行創建的問題。 (file.component.ts

 rawFile.send(null);

如果你需要更多的文件,告訴我。

以下是文件

file.component.ts

import { Component, OnInit } from '@angular/core'; 

@Component(
{ 
selector: "file", 
templateUrl: "/filedata.component.html", 
}) 
export class FileData 
{ 
makeRequest(file) 
{ 
    let rawFile = new XMLHttpRequest(); 
    rawFile.open("GET", file, false); 
    try 
    { 
     rawFile.onreadystatechange =() => 
     { 
      if(rawFile.readyState === 4) 
      { 
       if(rawFile.status === 200 || rawFile.status == 0) 
       { 
        var allText = rawFile.responseText; 
        console.log(allText); // Here is the contents of the file 
       } 
       else 
        console.log("error contents"); 
      } 
      else 
       console.log("error ready status"); 
     } 
     rawFile.send(null); // Here's the Error! 
    } 
    catch(e) 
    { 
     console.log(e); 
    } 
} 
} 

file.component.html

<div> 
<button type = "button" (click) = "makeRequest('E:/xampp/Angular-cli/Login/src/app/employees.txt')">File Test</button> 
</div> 

回答

0

我認爲你必須在函數調用指定file:///

<button type = "button" (click) = "makeRequest('file:///E:/xampp/Angular-cli/Login/src/app/employees.txt')">File Test</button>

+0

沒有發生。 :/。它永遠不會執行 ** if(rawFile.readyState === 4)** –