I'm trying to connect my Django backend to a React Frontend using axios to access the api endpoint. I have tested the api using curl to see if I receive a json of the test data, it is fine. I have opened up the endpoint so that it does not need authentication. But I keep on getting this error in my javascript console:
edit: for to say that I am running the api and frontend on my computer
Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:87)
Test.js- Test component to test out feeding backend to frontend. I would like to console log the data but only catch the error.
import React, {Component} from 'react'
import axios from 'axios';
class Test extends Component{
constructor(){
super();
this.state = {
messages:[],
}
}
componentDidMount(){
axios.get('http://127.0.0.1:8000/api/message/?format=json')
.then(res=> {
console.log(res);
})
.catch(error =>{
console.log(error);
});
}
render(){
return(
<div>
<h1>
Message:
</h1>
</div>
)
}
}
export default Test;
I needed to setup CORS on my django api. The issue was not with my front end but by backend not being setup properly. Whenever you have api request from a different server you have to setup CORS on the backend.
Related
My code currently consists of a frontend in react and a flask backend api. I'm trying to establish a session in my backend using flask sessions, but I'm unable to, since flask never makes contact with the user, and all requests go through the frontend. To that end, I'm trying to post cookies to
In the frontend, I have something like
import Cookies from 'universal-cookie';
class thingy extends React.Component{
constructor(props) {
this.backendurl = 'localhost:5000'
const cookies = new Cookies();
this.username = this.props.match.params.user
cookies.set('UserName', ''+JSON.stringify(this.username), { path:
'/profile' });
}
onclick = ()=>{
#post something using axios that sends the cookie to the flask backend so it can be processed
}
}
render(){
return(
<button onClick = {this.onclick}>Click Here</button>
)
}
}
backend:
app = Flask(__name__)
app.config["SESSION_PERMANENT"] = False
Session(app)
#app.route('/user',methods=['POST'])
def info():
#do something with the cookie that react posted in order to user flask_session
return user.name
Does someone know how to send the cookies from react to flask, and then input the cookies recieved by flask into the flask session?
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
i'm trying to access express.js routes from react front end but i don't seem to get how to go about it. my express.js backend runs on localhost:9000 and my react frontend runs on localhost:3000. this is my react code;
import React from 'react';
import './App.css';
import {BrowserRouter as Router, Link} from 'react-router-dom';
class App extends React.Component {
constructor(props) {
super(props);
this.state = { apiResponse: "" };
}
callAPI() {
fetch("http://localhost:9000/:username")
.then(res => res.text())
.then(res => this.setState({ apiResponse: res }));
}
componentWillMount() {
this.callAPI();
}
render(){
return (
<div className="App">
<p>{this.state.apiResponse}</p>
</div>
);
}
}
export default App;
i have created two files on express routes folder, one is testAPI.js and the other is be.js. when i try to acces any of these two files from my browser without using react, on lets say localhost:9000/testAPI it works fine. but when i try to access localhost:3000/testAPI which calls the same file through react, it gives me this messed up error page:
<!DOCTYPE html><html><head><title></title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>Not Found</h1><h2>404</h2><pre>NotFoundError: Not Found at C:\Users\Denoh\full\api\app.js:33:8 at Layer.handle [as handle_request] (C:\Users\Denoh\full\api\node_modules\express\lib\router\layer.js:95:5) at trim_prefix (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:317:13) at C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:284:7 at Function.process_params (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:335:12) at next (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:275:10) at C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:635:15 at next (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:260:14) at Function.handle (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:174:3) at router (C:\Users\Denoh\full\api\node_modules\express\lib\router\index.js:47:12)</pre></body></html>
please assist
you need to use proxy in package.json to achieve this
basically you set the url you want to proxy too so that React knows how to connect to your server
see this for more info: https://create-react-app.dev/docs/proxying-api-requests-in-development/
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.
I've been banging my head trying to figure this out. I'm trying to call Yelp's API using axios, but I'm getting the following errors.
OPTIONS https://api.yelp.com/v3/businesses/search 403
Failed to load https://api.yelp.com/v3/businesses/search: Response for
preflight does not have HTTP ok status.
I took care of the CORS issue by turning CORS off with a chrome extension. I've tested the API request successfully with Postman, so there isn't any issues with the Bearer token I'm using or the URL.
Below is the code I'm using to call the API.
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import axios from 'axios';
const config = {
headers: {'Authorization': 'Bearer token'},
};
class Results extends Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items: []
};
}
componentWillMount() {
axios.get('https://api.yelp.com/v3/businesses/search', config)
.then(response => console.log(response));
}