通过API将Node / Express后端MQTT订户数据发送到React Native前端吗?

时间:2020-04-27 12:17:36

标签: javascript node.js react-native express

我正在努力创建带有Node / Express后端的React Native前端。这个想法是,后端连接到AWS Iot Core,订阅一个主题,并通过API将传感器数据发送到React Native前端。关于后端,我可以成功订阅MQTT主题,生成GET请求并将数据发送到端口5000上的服务器。运行应用程序时出现问题,我收到TypeError:null不是一个对象(评估为'this。状态。天气')

Full screenshot of the error message

我不知道如何解决该错误,因此将不胜感激。

后端/app.js

const awsIot = require('aws-iot-device-sdk');
const express = require('express');

const app = express();

const device = awsIot.device({
  keyPath: "C:\\Users\\l9val\\Desktop\\NewThing\\private.pem.key",
  certPath: "C:\\Users\\l9val\\Desktop\\NewThing\\certificate.pem.crt",
  caPath: "C:\\Users\\l9val\\Desktop\\NewThing\\AmazonRootCA1.pem",
  clientId: Math.random().toString(36).substring(2, 15),
  host: "xxxxxxxxxxxxxx-ats.iot.us-east-1.amazonaws.com"
});

device.on('connect', () => {
  device.subscribe('topic/sensor_one');
});

device.on('message', (topic, payload) => {
  app.get('/', (req, res) => {
    var data = JSON.parse(payload.toString());
    var temp_c = data["current"]["temp_c"];
    res.send({ temp_c });
  });
});

app.listen(process.env.PORT || 5000);

backend / package.json

{
  "name": "backend",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "aws-iot-device-sdk": "^2.2.4",
    "express": "^4.17.1"
  }
}

frontend / Weather.js

import React, { Component } from 'react';
import { Text, View } from 'react-native';
import axios from 'axios';

export default class Weather extends Component {
  componentDidMount() {
    axios.get('/').then(response => {
      this.setState({
        weather: response.data.temp_c
      });
    });
  };

  render() {
    return (
      <View>
        <Text>
          Sensor 1: {this.state.weather} degrees Celsius
        </Text>
      </View>
    );
  };
};

frontend / App.js

import React from 'react';
import { View } from 'react-native';
import Weather from "./Weather";

export default function App() {
  return (
    <View>
      <Weather />
    </View>
  );
};

frontend / package.json

{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject"
  },
  "dependencies": {
    "axios": "^0.19.2",
    "expo": "~37.0.3",
    "react": "~16.9.0",
    "react-dom": "~16.9.0",
    "react-native": "https://github.com/expo/react-native/archive/sdk-37.0.1.tar.gz",
    "react-native-web": "~0.11.7"
  },
  "devDependencies": {
    "babel-preset-expo": "~8.1.0",
    "@babel/core": "^7.8.6"
  },
  "private": true,
  "proxy": "http://localhost:5000/"
}

0 个答案:

没有答案