I am trying to emit an event originally from my backend to my front end using "socketio.emit" however it is not getting received in react
Backend:
#app.route('/')
#cross_origin()
def receive_data():
socketio.emit("test")
return "h1"
Frontend
useEffect(() => {
socket.on("test", ()=>{
alert("twitchchat")
})
}
Any help would be appreciated thanks
Related
I am using React.js 18 version. Facing CORS issue on a piece of code while making post request using axios. Intentionally not putting the original URL of post request. Attaching API response screenshot files below the code.
I am getting response in postman but not in browser(CORS). All I know from my colleague, this API is build on PHP and according to backend guy things are fine on his side.
I am putting this code here to know what are we doing wrong on front end? We are stuck here since yesterday.
Please help!
console response : https://i.stack.imgur.com/HbUjq.png
network response : https://i.stack.imgur.com/6xycq.png
network response : https://i.stack.imgur.com/5cjey.png
postman response : https://i.stack.imgur.com/MxyDT.png
import React, {useState, useEffect} from 'react';
import axios from 'axios';
import './App.css';
function App() {
const [CaseDetail, setCaseDetail] = useState([]);
const getCaseDetail = async () => {
const casedetail = {schemeNameDratDrtId:'1',casetypeId:'1',caseNo:'1',caseYear:"2020"};
await axios.post('URL', casedetail,
{
headers: {"Access-Control-Allow-Origin": "*"}
}
)
.then((result) => {
setCaseDetail(result.data.data)
})
}
useEffect(() => {
getCaseDetail();
}, []);
console.log(CaseDetail)
return (
<div className="App">
<h2>Welcome to Home Page</h2>
</div>
);
}
export default App;
Your server should enable the cross-origin requests, not the client. To do this, you can check this nice page with implementations and configurations for multiple platforms
This is a security issue from the browser. If you get 200 using postman, this means the problem is that the browser is blocking it. Try to play this again using API testing website like: "reqbin.com", if that works, the backend guys should fix the header problem. I hope this helps.
some possiable things that might help:
I am getting response in postman but not in browser(CORS) - this is noraml for CORS problem.
there can be a differnce betweeen fetach and axios requests. so check if fetach works. if so check
Axios fails CORS but fetch works fine
if you need to send a token in a header , make sure that the axios sends it
see
How to set header and options in axios?
I am working on a simple React-Flask App which aims to fetch the current time from the Back-end and display it on the Front-end.
I have the Flask Back-end and the React Front-end both running together at the same time.
The back-end is working perfectly fine on port 5000:
Back-end
Fetch call '/time' from the front-end is unable to fetch the current time even tho I have my proxy defined in the package.json:
"proxy": "http://localhost:5000"
Front-end:
function App() {
const [currentTime, setCurrentTime] = useState(0);
const getCurrentTime = async (API) => {
const response = await fetch(API);
const jsonData = await response.json();
setCurrentTime(jsonData.time);
console.log(jsonData);
};
useEffect(() => {
// getCurrentTime('http://localhost:5000/time');
getCurrentTime('/time');
}, []);
I have tried the methods discussed here. But none of them seems to work for me.
"proxy": "http://127.0.0.1:5000". this solution worked for me. The reason why I was getting this error is that I didn't know that I have to restart the development server after making changes in the package.json.
This worked for me
I'm trying to stream data every second from my server to the frontend. Currently I could only connect to the socket io and all the tutorials I found was using a chat application as an example.
The project consist of pymodbus so I could communicate to a plc and gather those data. The data is then visualize using reactjs
Python
from flask import Flask, jsonify
from flask_restful import Api, Resource
from flask_socketio import SocketIO, emit
import random
app = Flask(__name__)
app.config["SECRET_KEY"] = "somethingRandom"
app.config["DEBUG"] = True
api = Api(app)
socketio = SocketIO(app, cors_allowed_origins="*")
#app.route("/")
def hello_world():
return jsonify(mssg="hello world")
def PlcTankData():
i = 5
j = 0
while j != 5: # should be while True
j+=1
sample = random.randint(1, 10)
print(sample)
emit("newdata", {"td": sample}, namespace="/home")
socketio.sleep(1)
#socketio.on("connect", namespace="/home")
def frontend_connection():
print("Client is Connected")
emit("connect", {"hello": "world"})
PlcTankData()
class MachineStatus(Resource):
def put(self):
data = request.json
print(data)
api.add_resource(MachineStatus, '/machine-stat')
if __name__ == '__main__':
socketio.run(app, host="192.168.0.105", port=5000)
Reactjs
import React, { useState, useEffect } from 'react'
import axios from 'axios'
import io from 'socket.io-client'
//To Control the machcine
const handleMachineStatus = async (e) => {
await axios
.put('http://192.168.0.105:5000/machine-status', { status: e.target.name })
.then((res) => {
console.log(res)
})
.catch((err) => console.log(err))
}
//To get real time data
useEffect(() => {
const socket = io.connect('http://192.168.0.105:5000/home')
socket.on('connect', (data) => console.log(data))
socket.on('newdata', (data) => console.log(data))
}, [])
I know that the while loop is the one causing the trouble cause the data is being thrown after the while loop is finish.
PS: I'm not sure if the react code also has a problem so I'll tag it.
The connect handler is not a good place to run a lengthy task, because Flask-SocketIO completes the connection process once you return from this handler.
I suggest you move your PlcTankData function to a separate event instead of calling it from the connect handler.
I have build a simple pure react and meteor web app. I am trying to connect a flask API to my meteor.js app for the machine learning component of my application. I have seen examples for pure react front end but cant get the same logic to work for meteor.
what I did is:
make a flask app and return the prediction results to localhost:5000 as a python dictionary e.g.
{'class': 'bird', 'confidence':'0.8932'}
Set up a proxy in my meteor app in package.json, I have meteor app running at localhost:3000:
"proxy":"http://127.0.0.1:5000/"
finally, this is where I am confused, I have a bunch of components in my home page, I am not sure if I have to render the flask results in a component or page, nor how to do that. What I tried Is to render the results in one of the components using the useEffect, useState functions.
I get an error that says something like I can't use this funtionality.
function App() {
const [predictedClass, setPredictedClass] = useState(0);
useEffect(() => {
fetch('/prediction').then(res => res.json()).then(data => {
setPredictedClass(data.class);
});
}, []);
I use the useEffect method to get the data from the requests of my api.
example:
const [data, setData] = useState(null);
useEffect(() => {
getData('GET', '/api/test')
.then(response => {
setData(response)
})
.catch(error =>
console.log(error)
);
}, []);
Where getData is a custom function that calls an axios request.
I have the following invocation of fetch in my React Native app:
test = async () => {
try {
let a = await fetch('https://rxapitest.alliancepharmacygroup.ca:12345/', {
method,
}).then(response => {
console.log("success")
})
} catch(err) {
console.log("error")
}
}
Normally I'm hitting actual endpoints from this API with a bearer token, but none of them is working, so I tried the more basic task of just hitting the web page itself. When I run this from Postman it works fine. I'm using React Native v0.62.1.
Does anyone know how I can approach this?