我正在使用angular-cli,我正在使用点击事件发送XMLHttpRequest来读取txt文件,并收到此错误。
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 :(得分:0)
我认为你必须在函数调用中指定file:///
<button type = "button" (click) = "makeRequest('file:///E:/xampp/Angular-cli/Login/src/app/employees.txt')">File Test</button>