OH3 Rest-API CORS or not to CORS

Dear OH Community,

HAPPY NEW YEAR and THANK YOU for continuously improving OpenHAB.

I am just migrating to OH3 and since I am having my own mobile enabled dashboard (AngularJS via API) I heavily rely on the OH3 API.

Where I get stuck is that my own dashboard complains about CORS policy

Access to XMLHttpRequest at 'http://172.27.1.31/rest/items/Netatmo_Outdoor_Temperature' from origin 'http://172.27.1.30' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Yet, I added the CORS enabled=true (that I used in OH2.5) to /conf/services/runtime.cfg

org.eclipse.smarthome.cors:enable=true

Maybe this is not the way that I am supposed to do this anymore, thus would be happy for help (did search the community, but not find it, so wondering if I do anything wrong the way I access the API that CORS comes to play at all).

If I open the API in my browser I can see all items and their values perfectly - only if I open the API from AngularJS I get this error message.

I do not do a ton of web development these days, and never really looked closely into CORS,… please excuse if it is a stupid approach :slight_smile:

Best
Jens

I do not know, but try

org.openhab.cors:enable=true
2 Likes

Hi Bruce,

thx it works - this was too obvious, should have seen that myself :roll_eyes:

Anyhow thx for pointing it out :slight_smile:

Would still be interested if there is a way w/o using the CORS enabled parameter.

Best

  • Jens

As example you can add to $OH_USERDATA/etc/org.ops4j.pax.web.cfg:

org.ops4j.pax.web.cors.enabled=true
org.ops4j.pax.web.cors.allow-origin=*
org.ops4j.pax.web.cors.allow-methods=GET,POST,PUT,DELETE,OPTIONS
org.ops4j.pax.web.cors.allow-headers=Authorization,Content-Type

If you mean your programme code. This is not possible because it would violate the Same-Origin-Policy.

I added those to my openhab instance and then wrote a typescript script to post a item, but get also a error code.

openhab.service:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class OpenhabDataServiceService {

  constructor(private http: HttpClient) {}

  sendRequest(itemName: string, command: string): Observable<any> {
    const url = `http://192.168.188.96:8080/rest/items/${itemName}`;
    
    // Setzen Sie den Content-Type auf text/plain
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'text/plain'
      })
    };

    // Führen Sie den POST-Request mit dem Befehl aus
    return this.http.post(url, command, httpOptions);
  }
}

import { Component } from '@angular/core';
import { RangeCustomEvent } from '@ionic/angular';
import { OpenhabDataServiceService } from '../openhab-data-service.service';

@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss']
})
export class Tab1Page {

  constructor(public openhabService: OpenhabDataServiceService) {}

  sendOpenhabCommand(itemName: string, command: string) {
    this.openhabService.sendRequest(itemName, command).subscribe(response => {
      if (response !== null) {
        // Überprüfen Sie, ob die Antwort ein gültiges JSON ist
        try {
          const responseData = JSON.parse(response);
          // Verarbeiten Sie die Antwortdaten hier
          console.log('Backend Response:', responseData);
        } catch (error) {
          console.error('Error parsing JSON response:', error);
        }
      } else {
        console.error('Backend Response is null');
      }
    }, error => {
      console.error('Error:', error);
    });
  }

  onIonChange(ev: Event) {
  
    this.sendOpenhabCommand('Hue_ambiance_candle_1_Brightness', '70')
    
  }

}

Error Code: Access to XMLHttpRequest at 'http://192.168.188.96:8080/rest/items/Hue_ambiance_candle_1_Brightness' from origin 'http://localhost:8100' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.