Ad

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 https://www.status.webcoder.sk but now I'm trying to do it in nodejs on https://www.webcoderstatus.herokuapp.com 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();
            request.open('GET', 'https://www.webcoder.sk/config/devices.txt', true);
            request.send(null);
            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();
            console.log(devices);
        });

This is the error message: (index):1 Access to XMLHttpRequest at 'https://www.webcoder.sk/config/devices.txt' from origin 'https://webcoderstatus.herokuapp.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Ad

Answer

Problem

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

Solution

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 https://www.webcoder.sk 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();
app.use(cors());

/*The rest of your routes*/
Ad
source: stackoverflow.com
Ad