So im getting the following error;
Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
I have googled this, and there are tonnes of people with this problem, and lots of solutions, however, non seem to work for me, or im implementing them incorrect...
Scenario - React app trying to call data from a Flask API.
Flask API code
app = Flask(__name__)
#app.route("/authURL")
def home():
data = {
"AuthURL":"www.google.com",
"test123":123
}
return jsonify(data)
React code
import { useEffect } from 'react';
function App() {
useEffect(() => {
fetch("/authURL")
.then(response => response.json()
.then(data => {
console.log(data)
})
)}, []);
return (
<div className="App">
<header className="App-header">
</header>
</div>
);
}
export default App;
The network suggests there is no issue with communicating between flask and react, ive tried to isolate the problem, and it seems to be with the data itself, but honestly not sure.
Any help is appreciated!
Thanks in advance
Related
My websocket works because i tested it from django side white simple chat app. The route also works which is http://localhost:8000/chat/room. But It doesnt work on react side. It says No route found for path 'chat/myroom'. I've been trying to solve this for 2 hours, as a last hope, I wanted to ask here.
My routing.py file
from django.urls import re_path
from api import consumers
websocket_urlpatterns = [
re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()),
]
My roomPage.js file
`import React from "react";
import useWebSocket, { ReadyState } from "react-use-websocket";
import { useParams } from "react-router-dom";
export default function RoomPage() {
const { readyState } = useWebSocket("ws://127.0.0.1:8000/chat/myroom", {
onOpen: () => {
console.log("Connected!");
},
onClose: () => {
console.log("Disconnected!");
}
});
const connectionStatus = {
[ReadyState.CONNECTING]: "Connecting",
[ReadyState.OPEN]: "Open",
[ReadyState.CLOSING]: "Closing",
[ReadyState.CLOSED]: "Closed",
[ReadyState.UNINSTANTIATED]: "Uninstantiated"
}[readyState];
return (
<div>
<span>The WebSocket is currently {connectionStatus}</span>
</div>
);
}`
I tried on django side and it worked! But react side doesn't working
After +10 hours i finally found the solution and I want to kill myself! The only problem is calling websocket without "end slash"
Wrong!
useWebSocket("ws://127.0.0.1:8000/chat/myroom"
Works
useWebSocket("ws://127.0.0.1:8000/chat/myroom/"
Working locally, I'm trying to pull some data from an api endpoint into a react front-end. Here's what I have:-
Data source/api endpoint (api platform, symfony)
http://127.0.0.1:8000/api/users?page=1
Front-end, React
http://127.0.0.1:3000/
/src/App.js
import React from 'react';
fetch('http://127.0.0.1:8000/api/users?page=1')
.then(response => console.log(response))
.then(json => console.log(json))
function App() {
return (
<div className="App">
</div>
);
}
export default App;
Firstly, I had to overcome a CORS issue with my data source. In symfony;-
.env
###> nelmio/cors-bundle ###
CORS_ALLOW_ORIGIN='^https?://(localhost|127\.0\.0\.1)(:[0-9]+)?$'
###< nelmio/cors-bundle ###
As a side note; For my api endpoint (data source) - I can return the json response fine using both cURL and postman. However, if I try directly in a browser address bar, I just get my api landing page back i.e. swagger doc.
I'm wondering if this is an issue with headers not being set?
Back in my react app http://127.0.0.1:3000/ and at the console;-
my response is showing a 200 as you can see from above, but my json variable has a length of zero? So, no data.
Any ideas on how to pull the data (json) through to my react app using the above technique?
Here's what I was looking for in the end...
import React from 'react';
import { useEffect } from 'react'
function App() {
useEffect(() => {
fetch("http://127.0.0.1:8000/api/users?page=1")
.then((response) => response.json())
.then((response) => {
console.log(response);
})
}, []);
return (
<div className="App">
</div>
);
}
export default App;
So basically the console is showing me that I have an unexpected token but I don't think there is any unexpected token. Please help me. I have taken way too much time trying to fix this problem. Here is the code -
import React from 'react';
import firebase from 'firebase';
export default function App() {
// I have deleted this information because I don't want anyone to access my data
const firebaseConfig = {};
firebase.initializeApp(firebaseConfig);
function signInWithGoogle() {
var google_provider = new firebase.auth.GoogleAuthProvider();
firebase
.auth()
.signInWithPopup(google_provider)
.then((res) => {
console.log(res);
})
.catch((error) => {
console.log(error);
});
}
return (
<div>
<h1>Google Sign In Authentication</h1>
<button onClick={signInWithGoogle}>Sign In</button>
</div>
);
}
The only issue I see in the provided code is you have not imported the Firebase Auth SDK. You can import that as shown below:
import firebase from 'firebase';
import "firebase/auth"
Also make sure you are using V8.X.X or lower with above code. If you have new Modular SDK V9.0.0+ then change your imports to compat version to keep using existing code:
import firebase from 'firebase/compat/app';
import "firebase/compat/auth"
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.
Already three days struggling to solve this problem so any help appreciated.
I have a simple component for check token from localStorage:
import Router from 'next/router';
const Blog = _ => {
const token = localStorage.getItem("token");
useEffect(_ => {
if(!token){
Router.push('/')
}
}, [])
}
This will work if we have a code like this:
<Link href="/blog">Blog</Link>
Then when you click blog you will be redirect to "/".
But if you type in browser url bar /blog and push enter you will not redirect to main page "/".
UPD:There is no token in localStorage
There are two problems with your code:
There is no return statement in the functional component. React throws an error if there is nothing returned.
If you type '/blog' in the browser, Nextjs throws an error, as the code is first run on the server( the server doesn't have a local storage - Error: localStorage is not defined). To resolve this you can do one of two things -
check whether the code is executing on the server or the client and then handle accordingly
move localStorage.getItem inside componentDidMount( or hooks equivalent).
import Router from "next/router";
import { useEffect } from "react";
const Blog = _ => {
useEffect(_ => {
const token = localStorage.getItem("token");
if (!token) {
Router.push("/");
}
}, []);
return <p>This is a blog</p>;
};
export default Blog;