-1

For my school project i'm using a hardware button linked to a Raspberry pi and have it give a true or false value based on the button press(coded in Python). This is saved on a local json file on the Pi and I get the value to a local website using javascript.

The problem is that I get this error in the console of my browser:

Access to XMLHttpRequest at 'file:///home/pi/website/button-status.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.

I've tested the code on my laptop and it works fine, only on the Pi it gives this error. I'm using chromium as my browser on the Pi.

Anyone knows why this happens and how to fix it? Thanks in advance!

Python code:

import json
import RPi.GPIO as GPIO
from time import sleep

GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)

waar = 1
nWaar = 0
button_status = False

path = "/home/pi/website"

def save_button_status():
    with open(path + "/button-status.json", "w") as f:
        json.dump({'status': button_status}, f)

while True:
    input_state = GPIO.input(17)

    if input_state == False :
        if waar == 1:
            print('Button Press True')
            button_status = True
            save_button_status()
            waar = 0
            nWaar = 1
            sleep(5)



    if input_state == True:
        if nWaar == 1:
            print('Button Press False')
            button_status = False
            save_button_status()
            waar = 1
            nWaar = 0

Javascript:

function get(url, success) {
console.log('hoi');
    //--- Get JSON data at the given URL and call success if successful
    const request = new XMLHttpRequest();
    request.open("GET", url, true);
    request.onreadystatechange = function() {
        if (request.readyState === 4 && request.status === 200) {
            success(JSON.parse(request.responseText));
        }
    };
    request.send();
}

function receiveStatus(response) {
    if (response.status !== status) {  // only do something if status has changed
        status = response.status;
        console.log('button status is now', status);
    }
}
let status;
let interval = setInterval(() => get("button-status.json", receiveStatus), 2000);
Sw3que
  • 31
  • 6

1 Answers1

-1

You should check out this Medium article I found, I think it should help solve your issue and understand CORS a little better here

All it's saying is that you just need to adjust the headers in your request to Allow a certain response from a certain location. It uses a URL but I figure a direct IP address should be ok if you're on a local network. If you're working away from the network you'll have to set up some Port Forwarding, and if it's a school project that might be tough with any network regulations they may have in place.

Joshua Boddy
  • 83
  • 1
  • 9