Weiter zum Inhalt
  • Home
  • Aktuell
  • Tags
  • 0 Ungelesen 0
  • Kategorien
  • Unreplied
  • Beliebt
  • GitHub
  • Docu
  • Hilfe
Skins
  • Hell
  • Brite
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dunkel
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Standard: (Kein Skin)
  • Kein Skin
Einklappen
ioBroker Logo

Community Forum

donate donate
  1. ioBroker Community Home
  2. Deutsch
  3. ioBroker Allgemein
  4. HTTP request verarbeiten

NEWS

  • Neuer ioBroker-Blog online: Monatsrückblick März/April 2026
    BluefoxB
    Bluefox
    8
    1
    1.7k

  • Verwendung von KI bitte immer deutlich kennzeichnen
    HomoranH
    Homoran
    10
    1
    696

  • Monatsrückblick Januar/Februar 2026 ist online!
    BluefoxB
    Bluefox
    18
    1
    1.2k

HTTP request verarbeiten

Geplant Angeheftet Gesperrt Verschoben ioBroker Allgemein
requesthttp
3 Beiträge 2 Kommentatoren 990 Aufrufe 3 Beobachtet
  • Älteste zuerst
  • Neuste zuerst
  • Meiste Stimmen
Antworten
  • In einem neuen Thema antworten
Anmelden zum Antworten
Dieses Thema wurde gelöscht. Nur Nutzer mit entsprechenden Rechten können es sehen.
  • T Offline
    T Offline
    thesnoopy
    schrieb am zuletzt editiert von
    #1

    Hi Community,
    ich programmiere gerade meinen ersten Adapter und verzweifel gerade an einem einfachen HTTP Request. Um mich mit der Materie vertraut zu machen wollte ich erst einmal einen einfachen request, in diesem Fall "http://api.ipify.org/?format=json" auslesen. Leider bekomme ich immer eine Fehlermeldung, wenn ich mir nur die Ausgabe anzeigen lassen möchte. Gleiches Problem, wenn ich über setState einen Status ändern möchte. Hier meine main.js:

    "use strict";
    
    /*
     * Created with @iobroker/create-adapter v1.29.1
     */
    
    // The adapter-core module gives you access to the core ioBroker functions
    // you need to create an adapter
    const utils = require("@iobroker/adapter-core");
    var request = require('request');
    
    // Load your modules here, e.g.:
    // const fs = require("fs");
    
    class Amadeus extends utils.Adapter {
    
    	/**
    	 * @param {Partial<utils.AdapterOptions>} [options={}]
    	 */
    	constructor(options) {
    		super({
    			...options,
    			name: "amadeus",
    		});
    		this.on("ready", this.onReady.bind(this));
    		this.on("stateChange", this.onStateChange.bind(this));
    		// this.on("objectChange", this.onObjectChange.bind(this));
    		// this.on("message", this.onMessage.bind(this));
    		this.on("unload", this.onUnload.bind(this));
    	}
    
    	/**
    	 * Is called when databases are connected and adapter received configuration.
    	 */
    	async onReady() {
    		// Initialize your adapter here
    
    		// The adapters config (in the instance object everything under the attribute "native") is accessible via
    		// this.config:
    		this.log.info("config option1: " + this.config.option1);
    		this.log.info("config option2: " + this.config.option2);
    		this.log.info("config option3: " + this.config.option3);
    
    		/*
    		For every state in the system there has to be also an object of type state
    		Here a simple template for a boolean variable named "testVariable"
    		Because every adapter instance uses its own unique namespace variable names can't collide with other adapters variables
    		*/
    		await this.setObjectNotExistsAsync("testVariable", {
    			type: "state",
    			common: {
    				name: "testVariable",
    				type: "boolean",
    				role: "indicator",
    				read: true,
    				write: true,
    			},
    			native: {},
    		});
    
    		// In order to get state updates, you need to subscribe to them. The following line adds a subscription for our variable we have created above.
    		this.subscribeStates("testVariable");
    		// You can also add a subscription for multiple states. The following line watches all states starting with "lights."
    		// this.subscribeStates("lights.*");
    		// Or, if you really must, you can also watch all states. Don't do this if you don't need to. Otherwise this will cause a lot of unnecessary load on the system:
    		// this.subscribeStates("*");
    
    		/*
    			setState examples
    			you will notice that each setState will cause the stateChange event to fire (because of above subscribeStates cmd)
    		*/
    		// the variable testVariable is set to true as command (ack=false)
    		await this.setStateAsync("testVariable", true);
    
    		// same thing, but the value is flagged "ack"
    		// ack should be always set to true if the value is received from or acknowledged from the target system
    		await this.setStateAsync("testVariable", { val: true, ack: true });
    
    		// same thing, but the state is deleted after 30s (getState will return null afterwards)
    		await this.setStateAsync("testVariable", { val: true, ack: true, expire: 30 });
    
    		// examples for the checkPassword/checkGroup functions
    		let result = await this.checkPasswordAsync("admin", "iobroker");
    		this.log.info("check user admin pw iobroker: " + result);
    
    		result = await this.checkGroupAsync("admin", "admin");
    		this.log.info("check group user admin group admin: " + result);
    //		var data = this.readData();
    		await this.main();
    	}
    
    	readData(){
    		var page = this.config.option3;
    		var options = {url: page, method: 'GET'};
    		request(options,function(error, response, body)
    			{
    				this.log.info(this.error);
    				this.log.info(this.response);
    				this.log.info(this.body);
    			})
    		}
    
    
    	main(){
    		try{
    			var data = this.readData();
    		}catch(e) {
    			this.log.error("Error while readData: " + e);
    		}
    	}
    	/**
    	 * Is called when adapter shuts down - callback has to be called under any circumstances!
    	 * @param {() => void} callback
    	 */
    	onUnload(callback) {
    		try {
    			// Here you must clear all timeouts or intervals that may still be active
    			// clearTimeout(timeout1);
    			// clearTimeout(timeout2);
    			// ...
    			// clearInterval(interval1);
    
    			callback();
    		} catch (e) {
    			callback();
    		}
    	}
    
    	// If you need to react to object changes, uncomment the following block and the corresponding line in the constructor.
    	// You also need to subscribe to the objects with `this.subscribeObjects`, similar to `this.subscribeStates`.
    	// /**
    	//  * Is called if a subscribed object changes
    	//  * @param {string} id
    	//  * @param {ioBroker.Object | null | undefined} obj
    	//  */
    	// onObjectChange(id, obj) {
    	// 	if (obj) {
    	// 		// The object was changed
    	// 		this.log.info(`object ${id} changed: ${JSON.stringify(obj)}`);
    	// 	} else {
    	// 		// The object was deleted
    	// 		this.log.info(`object ${id} deleted`);
    	// 	}
    	// }
    
    	/**
    	 * Is called if a subscribed state changes
    	 * @param {string} id
    	 * @param {ioBroker.State | null | undefined} state
    	 */
    	onStateChange(id, state) {
    		if (state) {
    			// The state was changed
    			this.log.info(`state ${id} changed: ${state.val} (ack = ${state.ack})`);
    		} else {
    			// The state was deleted
    			this.log.info(`state ${id} deleted`);
    		}
    	}
    
    	// If you need to accept messages in your adapter, uncomment the following block and the corresponding line in the constructor.
    	// /**
    	//  * Some message was sent to this instance over message box. Used by email, pushover, text2speech, ...
    	//  * Using this method requires "common.message" property to be set to true in io-package.json
    	//  * @param {ioBroker.Message} obj
    	//  */
    	// onMessage(obj) {
    	// 	if (typeof obj === "object" && obj.message) {
    	// 		if (obj.command === "send") {
    	// 			// e.g. send email or pushover or whatever
    	// 			this.log.info("send command");
    
    	// 			// Send response in callback if required
    	// 			if (obj.callback) this.sendTo(obj.from, obj.command, "Message received", obj.callback);
    	// 		}
    	// 	}
    	// }
    
    }
    
    // @ts-ignore parent is a valid property on module
    if (module.parent) {
    	// Export the constructor in compact mode
    	/**
    	 * @param {Partial<utils.AdapterOptions>} [options={}]
    	 */
    	module.exports = (options) => new Amadeus(options);
    } else {
    	// otherwise start the instance directly
    	new Amadeus();
    }
    
    

    Die Fehlermeldung lautet:

    (32115) TypeError: Cannot read property 'info' of undefined at Request._callback (/opt/iobroker/node_modules/iobroker.amadeus/main.js:97:14) at Request.self.callback (/opt/iobroker/node_module
    

    Ich denke es ist nur eine Kleinigkeit, die ich logisch falsch mache, allerdings komme ich da nicht drauf.

    Gruß,
    Carsten

    AlCalzoneA 1 Antwort Letzte Antwort
    0
    • T thesnoopy

      Hi Community,
      ich programmiere gerade meinen ersten Adapter und verzweifel gerade an einem einfachen HTTP Request. Um mich mit der Materie vertraut zu machen wollte ich erst einmal einen einfachen request, in diesem Fall "http://api.ipify.org/?format=json" auslesen. Leider bekomme ich immer eine Fehlermeldung, wenn ich mir nur die Ausgabe anzeigen lassen möchte. Gleiches Problem, wenn ich über setState einen Status ändern möchte. Hier meine main.js:

      "use strict";
      
      /*
       * Created with @iobroker/create-adapter v1.29.1
       */
      
      // The adapter-core module gives you access to the core ioBroker functions
      // you need to create an adapter
      const utils = require("@iobroker/adapter-core");
      var request = require('request');
      
      // Load your modules here, e.g.:
      // const fs = require("fs");
      
      class Amadeus extends utils.Adapter {
      
      	/**
      	 * @param {Partial<utils.AdapterOptions>} [options={}]
      	 */
      	constructor(options) {
      		super({
      			...options,
      			name: "amadeus",
      		});
      		this.on("ready", this.onReady.bind(this));
      		this.on("stateChange", this.onStateChange.bind(this));
      		// this.on("objectChange", this.onObjectChange.bind(this));
      		// this.on("message", this.onMessage.bind(this));
      		this.on("unload", this.onUnload.bind(this));
      	}
      
      	/**
      	 * Is called when databases are connected and adapter received configuration.
      	 */
      	async onReady() {
      		// Initialize your adapter here
      
      		// The adapters config (in the instance object everything under the attribute "native") is accessible via
      		// this.config:
      		this.log.info("config option1: " + this.config.option1);
      		this.log.info("config option2: " + this.config.option2);
      		this.log.info("config option3: " + this.config.option3);
      
      		/*
      		For every state in the system there has to be also an object of type state
      		Here a simple template for a boolean variable named "testVariable"
      		Because every adapter instance uses its own unique namespace variable names can't collide with other adapters variables
      		*/
      		await this.setObjectNotExistsAsync("testVariable", {
      			type: "state",
      			common: {
      				name: "testVariable",
      				type: "boolean",
      				role: "indicator",
      				read: true,
      				write: true,
      			},
      			native: {},
      		});
      
      		// In order to get state updates, you need to subscribe to them. The following line adds a subscription for our variable we have created above.
      		this.subscribeStates("testVariable");
      		// You can also add a subscription for multiple states. The following line watches all states starting with "lights."
      		// this.subscribeStates("lights.*");
      		// Or, if you really must, you can also watch all states. Don't do this if you don't need to. Otherwise this will cause a lot of unnecessary load on the system:
      		// this.subscribeStates("*");
      
      		/*
      			setState examples
      			you will notice that each setState will cause the stateChange event to fire (because of above subscribeStates cmd)
      		*/
      		// the variable testVariable is set to true as command (ack=false)
      		await this.setStateAsync("testVariable", true);
      
      		// same thing, but the value is flagged "ack"
      		// ack should be always set to true if the value is received from or acknowledged from the target system
      		await this.setStateAsync("testVariable", { val: true, ack: true });
      
      		// same thing, but the state is deleted after 30s (getState will return null afterwards)
      		await this.setStateAsync("testVariable", { val: true, ack: true, expire: 30 });
      
      		// examples for the checkPassword/checkGroup functions
      		let result = await this.checkPasswordAsync("admin", "iobroker");
      		this.log.info("check user admin pw iobroker: " + result);
      
      		result = await this.checkGroupAsync("admin", "admin");
      		this.log.info("check group user admin group admin: " + result);
      //		var data = this.readData();
      		await this.main();
      	}
      
      	readData(){
      		var page = this.config.option3;
      		var options = {url: page, method: 'GET'};
      		request(options,function(error, response, body)
      			{
      				this.log.info(this.error);
      				this.log.info(this.response);
      				this.log.info(this.body);
      			})
      		}
      
      
      	main(){
      		try{
      			var data = this.readData();
      		}catch(e) {
      			this.log.error("Error while readData: " + e);
      		}
      	}
      	/**
      	 * Is called when adapter shuts down - callback has to be called under any circumstances!
      	 * @param {() => void} callback
      	 */
      	onUnload(callback) {
      		try {
      			// Here you must clear all timeouts or intervals that may still be active
      			// clearTimeout(timeout1);
      			// clearTimeout(timeout2);
      			// ...
      			// clearInterval(interval1);
      
      			callback();
      		} catch (e) {
      			callback();
      		}
      	}
      
      	// If you need to react to object changes, uncomment the following block and the corresponding line in the constructor.
      	// You also need to subscribe to the objects with `this.subscribeObjects`, similar to `this.subscribeStates`.
      	// /**
      	//  * Is called if a subscribed object changes
      	//  * @param {string} id
      	//  * @param {ioBroker.Object | null | undefined} obj
      	//  */
      	// onObjectChange(id, obj) {
      	// 	if (obj) {
      	// 		// The object was changed
      	// 		this.log.info(`object ${id} changed: ${JSON.stringify(obj)}`);
      	// 	} else {
      	// 		// The object was deleted
      	// 		this.log.info(`object ${id} deleted`);
      	// 	}
      	// }
      
      	/**
      	 * Is called if a subscribed state changes
      	 * @param {string} id
      	 * @param {ioBroker.State | null | undefined} state
      	 */
      	onStateChange(id, state) {
      		if (state) {
      			// The state was changed
      			this.log.info(`state ${id} changed: ${state.val} (ack = ${state.ack})`);
      		} else {
      			// The state was deleted
      			this.log.info(`state ${id} deleted`);
      		}
      	}
      
      	// If you need to accept messages in your adapter, uncomment the following block and the corresponding line in the constructor.
      	// /**
      	//  * Some message was sent to this instance over message box. Used by email, pushover, text2speech, ...
      	//  * Using this method requires "common.message" property to be set to true in io-package.json
      	//  * @param {ioBroker.Message} obj
      	//  */
      	// onMessage(obj) {
      	// 	if (typeof obj === "object" && obj.message) {
      	// 		if (obj.command === "send") {
      	// 			// e.g. send email or pushover or whatever
      	// 			this.log.info("send command");
      
      	// 			// Send response in callback if required
      	// 			if (obj.callback) this.sendTo(obj.from, obj.command, "Message received", obj.callback);
      	// 		}
      	// 	}
      	// }
      
      }
      
      // @ts-ignore parent is a valid property on module
      if (module.parent) {
      	// Export the constructor in compact mode
      	/**
      	 * @param {Partial<utils.AdapterOptions>} [options={}]
      	 */
      	module.exports = (options) => new Amadeus(options);
      } else {
      	// otherwise start the instance directly
      	new Amadeus();
      }
      
      

      Die Fehlermeldung lautet:

      (32115) TypeError: Cannot read property 'info' of undefined at Request._callback (/opt/iobroker/node_modules/iobroker.amadeus/main.js:97:14) at Request.self.callback (/opt/iobroker/node_module
      

      Ich denke es ist nur eine Kleinigkeit, die ich logisch falsch mache, allerdings komme ich da nicht drauf.

      Gruß,
      Carsten

      AlCalzoneA Offline
      AlCalzoneA Offline
      AlCalzone
      Developer
      schrieb am zuletzt editiert von AlCalzone
      #2

      @thesnoopy
      Mehrere Fehler:

      1. Zeile 95
        Du verwendest einen function () callback, versuchst aber auf das this von außerhalb zuzugreifen. Das ist eine JavaScript-Eigenheit, dass this in manchen Funktionen keinen Wert hat. Zu diesem Zweck gibt es Arrow-Funktionen:
      request(options, (error, response, body) => {
        ...
        // hier ist mit `this.` auch wirklich die Adapter-Instanz gemeint.
      });
      
      1. Zeile 97-99:
        this.error, this.response und this.body gibt es nicht. Lass hier das this. weg, du willst ja die Parameter der Funktion nutzen.

      Warum `sudo` böse ist: https://forum.iobroker.net/post/17109

      T 1 Antwort Letzte Antwort
      1
      • AlCalzoneA AlCalzone

        @thesnoopy
        Mehrere Fehler:

        1. Zeile 95
          Du verwendest einen function () callback, versuchst aber auf das this von außerhalb zuzugreifen. Das ist eine JavaScript-Eigenheit, dass this in manchen Funktionen keinen Wert hat. Zu diesem Zweck gibt es Arrow-Funktionen:
        request(options, (error, response, body) => {
          ...
          // hier ist mit `this.` auch wirklich die Adapter-Instanz gemeint.
        });
        
        1. Zeile 97-99:
          this.error, this.response und this.body gibt es nicht. Lass hier das this. weg, du willst ja die Parameter der Funktion nutzen.
        T Offline
        T Offline
        thesnoopy
        schrieb am zuletzt editiert von
        #3

        @AlCalzone Vielen dank, das war es.

        1 Antwort Letzte Antwort
        0

        Hey! Du scheinst an dieser Unterhaltung interessiert zu sein, hast aber noch kein Konto.

        Hast du es satt, bei jedem Besuch durch die gleichen Beiträge zu scrollen? Wenn du dich für ein Konto anmeldest, kommst du immer genau dorthin zurück, wo du zuvor warst, und kannst dich über neue Antworten benachrichtigen lassen (entweder per E-Mail oder Push-Benachrichtigung). Du kannst auch Lesezeichen speichern und Beiträge positiv bewerten, um anderen Community-Mitgliedern deine Wertschätzung zu zeigen.

        Mit deinem Input könnte dieser Beitrag noch besser werden 💗

        Registrieren Anmelden
        Antworten
        • In einem neuen Thema antworten
        Anmelden zum Antworten
        • Älteste zuerst
        • Neuste zuerst
        • Meiste Stimmen


        Support us

        ioBroker
        Community Adapters
        Donate
        FAQ Cloud / IOT
        HowTo: Node.js-Update
        HowTo: Backup/Restore
        Downloads
        BLOG

        274

        Online

        32.9k

        Benutzer

        83.0k

        Themen

        1.3m

        Beiträge
        Community
        Impressum | Datenschutz-Bestimmungen | Nutzungsbedingungen | Einwilligungseinstellungen
        ioBroker Community 2014-2025
        logo
        • Anmelden

        • Du hast noch kein Konto? Registrieren

        • Anmelden oder registrieren, um zu suchen
        • Erster Beitrag
          Letzter Beitrag
        0
        • Home
        • Aktuell
        • Tags
        • Ungelesen 0
        • Kategorien
        • Unreplied
        • Beliebt
        • GitHub
        • Docu
        • Hilfe