The operation is insecure in React using MQTT package from npm - reactjs

I have a little app that gets sensor data and i want to use mqtt to distribute them. I've found this package on npm called MQTT, with this i can make a client in the browser, if i'm using an http insecure connection it works fine but when i use https i get an error in the create-react-app development server saying that this:
this.client = mqtt.connect();
It's an 'Insecure operation', someone had this problem or know any solution?
Also, in the wiki there is not an entry for a secure connection or something similar.
EDIT: the component code:
import React from 'react';
import mqtt from 'mqtt'
class MqttComponent extends React.Component {
constructor(props) {
super(props);
this.client = mqtt.connect();
this.client.on('connect', () => {
console.log(`connected`);
})
this.client.on('message', (topic, message) => {
let payload = JSON.parse(message);
let payloadKey = topic.substring(1);
console.log('message');
this.props.actualizarPorMensaje(payload, payloadKey);
});
}
componentDidUpdate(prevProps) {
Object.keys(this.props.equipos)
.filter(numeroSerie => !(numeroSerie in prevProps.equipos))
.map(numeroSerie => (
this.client.subscribe(`/${numeroSerie}`)
)
);
}
render() {
return;
}
}
export default MqttComponent;

Related

How to send data from ReactJs to signalR? In Asp.net Mvc Web Api

Im getting a problem when i want to send data from React Component to hub It's Not send...
Note Hub is connected to client But Data Not Send/Recieve
Hub Code
public void SendMessageToAll(string userName, string message)
{
Clients.All.messageReceived(userName, message );
}
React Js Code:
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { hubConnection } from 'signalr-no-jquery';
class Dashboard extends Component {
constructor(props) {
super(props);
const connection = hubConnection('https://localhost:44332');
const hubProxy = connection.createHubProxy('Chat');
hubProxy.on('Hello', function(name) {
console.log(name);
});
// atempt connection, and handle errors
connection.start()
.done(function(){ console.log('Now connected, connection ID=' + connection.id); })
.fail(function(){ console.log('Could not connect'); });
}
render() {
return (
<div/>
);
}
}
export default Dashboard;
Generally, when using SignalR, we will create the ChatHub.cs, which contains the send/receive method. In the client side, we will declare a proxy to reference the hub and connect the hub, then, we can call the hub's send/receive method to transfer the message. But from your code, I didn't find where you call the "SendMessageToAll()" method, so the message will not send. Please check your code.
Here are some tutorials about using SignalR, you can check them:
Chat Application Using ASP.NET, ReactJS, Web API, SignalR and Gulp
Tutorial: Real-time chat with SignalR 2

Create a Flask and React Full Stack Application

How do I create a website with a React Front end and a Flask backend?
I have created websites using flask and templates, and I have made pages using react, and now I would like to combine them.
I have tried a few things and the only things that worked required going into react config files and were very complicated. And even then it was complicated to use fetch and I had to run npm run build every time I changed the react file.
This seems to me like something that would be done all of the time yet I can't find any simple resources to do this.
Is there something that I fundamentally don't understand regarding websites and I am going at this the wrong way?
Focusing on a development workflow, as there are countless choices in how to deploy to a production environment.
Run your Flask app with /api as the root url prefix, either manually by prefixing all your route decorators or with the use of a Blueprint.
py/app.py
#app.route('/api')
def index():
return {'message':'hello'}
Add the Flask development server url to your package.json file
js/package.json
{
...,
"proxy": "http://localhost:5000"
}
Fetch your data using a component
js/Flask.js
import React, { Component } from 'react'
export class Flask extends Component {
constructor(props) {
super(props)
this.state = { data: {}, status: null }
}
fetchData() {
let status
fetch('/api')
.then((res) => {
return {
data: res.json(),
status: status
}
})
.then((data) => {
this.setState({ ...data })
}
.catch((err) => {
console.error(err)
})
}
componentDidMount() {
this.fetchData()
}
render() {
const { data, status } = this.state
return (
<div>
<h3>Status: { status }</h3>
<pre>
{ JSON.stringify(data) }
</pre>
</div>
)
}
}
export default Flask
Finally, include the component in your main App
js/App.js
import React from 'react';
import Flask from './Flask'
function App() {
return (
<div className="App">
<Flask />
</div>
);
}
export default App;
Start your Flask server with your preferred method, either flask run or by executing your script directly, then start your JS development server with either yarn or npm start. You should see the response from your api route displayed at http://localhost:8000
As long as you are running your Flask server with debug=True and use npm start (not npm run build), any changes made with either the backend or frontend will be automatically detected and your app reloaded.

Retrieving data from a local json file in react

How can i retrieve some data from a local json file i created in my folder? i´m using the following code:
class Intro2 extends Component {
render() {
async function getData() {
const usersData = await fetch("../articles.json");
const users = await usersData.json();
return users;
}
}
This doesn't seem to work for my local json file but if i use a url from git hub users for example its working?
many thanks
The error: main.chunk.js:332 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
You shouldn't be using fetch.
Use import instead. This will ensure webpack doesn't bundle the json file.
But makes it available in the public directory.
const usersData = await import("../articles.json");
Fetch will never work because webpack won't serve your JSON file.
Not unless you put it in a the static or public folder.
I think if you're trying to read from your file system you won't be able to do it, because in at least some browsers, you will need to serve the file via a web server process.
But if you are trying to read from http://localhost:9000/articles.json the issue could be another thing.
Maybe you need the {mode:'no-cors'} param ?
fetch('../static/test.txt', {mode: 'no-cors'})
Else you could simply export it:
export const json = () => ({...})
and then import it to your file:
import {json} from '../json
Assuming the json is in the project's folder structure.
import React from "react";
import ReactDom from "react-dom";
import usersData from "../articles.json";
class Intro2 extends React.Component {
state = {
usersData: { ...usersData },
};
componentDidMount() {
// a place for promises
};
render() {
// where the jsx is rendered
return <div>Renders JSX with state {this.state.usersData.aKey}</div>;
}
};
or with react functional components
// Alternatively, use functional components:
import React from "react";
import usersData from "../articles.json";
function Intro2() {
const [usersData, setUsersData] = React.useState({ ...usersData });
return <div>Renders JSX with state {usersData.aKey}</div>;
}

Unable to send push notifications from Firebase console using react-native-firebase

I am trying to send a push notification to my ios device from the Firebase console by token ID. I am using react-native-firebase to allow the app to perform actions based on the notification events. I followed the instructions to integrate the SDK and have set up the APNS certs etc:
http://invertase.io/react-native-firebase/#/installation-ios
My firebase.js config file looks like this:
import RNFirebase from 'react-native-firebase';
const configurationOptions = {
debug: true
};
const firebase = RNFirebase.initializeApp(configurationOptions);
export default firebase;
My main React component looks like this:
import React, { Component } from 'react'
import {
Text,
View,
Alert,
Platform
} from 'react-native'
import firebase from './firebase'
export default class extends Component {
constructor(props) {
super(props)
this.state = {
token: ''
}
}
componentDidMount() {
firebase.messaging().getToken()
.then((token) => {
this.setState({ token })
console.log('token: ', token)
})
firebase.messaging().getInitialNotification()
.then((notification) => {
console.log('Notification which opened the app: ', notification)
})
firebase.messaging().onMessage((message) => {
console.log('messaging', message)
})
firebase.messaging().onTokenRefresh((token) => {
console.log('Refreshed FCM token: ', token)
})
}
render() {
return (
<View style={{ marginTop: 22 }}>
<Text>{this.state.token}</Text>
</View>
)
}
}
I successfully get the token when the component mounts and then use that in the Firebase console to send a notification, but the notification is not received. I am using a real device, not and iPhone. I am using a development provisioning profile with Push notifications enabled and the remove notifications back ground entitlement enabled successfully, along with the appropriate development APNs certificate, which has been uploaded to the firebase console.
Why am I not receiving the notification on the device?
Okay, it looks like it was just ignoring the remote notifications because I had not requested permissions from the user. Just needed to do that via the SDK:
componentDidMount() {
firebase.messaging().requestPermissions()
firebase.messageing().getToken().then...

Integrating Relay with Redux in React Native App

I am new to react-native.My application currently uses redux,react-redux,router flux & navigator.
The back end i need to work with is GraphQL. What should i do now?
Can i integrate Relay to my app without affecting anything related to redux or should i dump redux and use relay?. What about lokka? Really confused!! Can someone help me with code examples or anything related to this issue?
Thanks in Advance :)
I use relay and redux in same application without much(I dont have any till today) issues(the App will be in production after few weeks). I could explain how I achieved it. (I am also new react-native and Js development, I don't claim this as the best approach, but at least it works for me as I intended)
Setting up of relay and graphQL almost took a day of effort. For this use following commands:-
npm install babel-core --save-dev
npm install babel-preset-react-native --save-dev
npm install babel-relay-plugin --save-dev
npm install react-relay --save
npm install graphql --save-dev
npm install sync-request --save-dev
then create a file named babelRelayPlugin.js and copy the below code.
const getBabelRelayPlugin = require('babel-relay-plugin')
const introspectionQuery = require('graphql/utilities').introspectionQuery
const request = require('sync-request')
const url = 'your_api_here'
const response = request('POST', url, {
qs: {
query: introspectionQuery
}
})
const schema = JSON.parse(response.body.toString('utf-8'))
module.exports = { plugins: [getBabelRelayPlugin(schema.data, { abortOnError: true })] }
and replace the code your .babelrc with this:-
{
"passPerPreset": true,
"presets": [
"./scripts/babelRelayPlugin",
"react-native"
]
}
following classes may need to use this import statement:-
import Relay, {
Route,
DefaultNetworkLayer
} from 'react-relay'
And my App.js file look like:-
function configureStore(initialState){
const enhancer = compose(applyMiddleware(
thunkMiddleware,
loggerMiddleware
),
autoRehydrate()
);
return createStore(reducer,initialState,enhancer);
}
const store = configureStore({});
persistStore(store, {storage: AsyncStorage})
////relay network layer injecting
Relay.injectNetworkLayer(new DefaultNetworkLayer('your_api'))
export default class App extends Component {
render() {
return (
<Provider store={store}>
{//here is your react-native-router-flux Navigation router}
<NavigationRouter/>
</Provider>
);
}
}
After injecting relay network layer, you could use the following code in any containers to call from relay. Here is an example render method of one of my containers:-
render() {
var value = 'some_value';
return (
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
<Relay.RootContainer
Component={TestComponent}
//relay_route is imported from relay_route.js
route={new relay_route({id:value})}
renderFetched={(data)=> {
return (
<TestComponent parentProps={this.props} {...data} />
);}}
/>
</View>
);
the relay_route.js should look something like
class relay_route extends Route {
static paramDefinitions = {
userID: { required: true }
}
static queries = {
user: () => Relay.QL`
query {
user(id: $userID)
}
`
}
static routeName = 'UserRoute'
}
And My TestComponent looks like:-
class TestComponent extends Component {
render () {
const user = this.props.user
return (
<Text>name: {user.name}</Text>
)
}
}
export default TestComponent = Relay.createContainer(TestComponent, {
fragments: {
user: () => Relay.QL`
fragment on User {
id,
name
}
`
}
})
For any doubts regarding relay, this documentation is classy to help us

Resources