No 'Access-Control-Allow-Origin' When Trying Get Data Of Text File From Url

I have the website with analytics of main site index. Earlier I had it in PHP on but now I'm trying to do it in nodejs on but I have 1 problem.

Get data from text file from url is working with no problems with php but when I'm trying to do it with JavaScript there is problem with CORS policy.

My code is:

        function getText(){
            var request = new XMLHttpRequest();
  'GET', '', true);
            request.onreadystatechange = function () {
                if (request.readyState === 4 && request.status === 200) {
                    var type = request.getResponseHeader('Content-Type');
                    if (type.indexOf("text") !== 1) {
                        return request.responseText;
        $(document).ready(function() {
            var devices = getText();

This is the error message: (index):1 Access to XMLHttpRequest at '' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.




This error is because you have your backend and frontend at different places(a.k.a origins). Your backend is hosted at and your frontend is at For security purposes browsers prevent access of data across different origins and by default implement same-origin policy policy.


What you need to do is enable Cross Origin Resource Sharing, which is nothing but to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin.

If you have control over the backend node.js service hosted at then here's a simple way to add CORS support.

  • First add the cors npm package to your node.js backend,
npm install --save cors
  • Then add the middleware to you starter file like this,
const express = require('express');
const cors = require('cors');

const app = express();

/*The rest of your routes*/