0
votes

I'm working with angular-cli, I'm reading txt file by sending XMLHttpRequest using click event and got this error.

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.

This is line creating problems. (file.component.ts)

 rawFile.send(null);

If you need more files, tell me.

Here are the files

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>
1

1 Answers

0
votes

I think you must specify file:/// in the function call

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