I want to post data from Vue to flask
If I don't use parameter data: {},it's no problem.
If I use, error occurs
and this is the server (HTTP Status Code is 200)
Why is this happening? What should I do?
code:
Home.vue
<script>
import axios from 'axios'
export default {
created() {
this.getData();
},
methods: {
getData() {
axios({
baseURL: 'http://127.0.0.1:5001',
url: '/recData',
method: 'post',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
}).then(res=>{
console.log(res);
}).catch(err=>{
console.log(err);
})
}
},
}
</script>
fls_2.py
from flask import Flask, request
from flask_cors import CORS
app = Flask(__name__)
CORS(app, resources={r'/*': {'origins': '*'}})
#app.route('/')
def index():
return 'Hello World!'
#app.route('/recData',methods=['GET','POST'])
def recData():
if request.method=='POST':
return '--- post ---'
if request.method=='GET':
return '--- get ---'
if __name__=='__main__':
app.run(port=5001, debug=True)
You can set a proxy in vue.config.js
module.exports = {
devServer: {
proxy: 'http://127.0.0.1:5001',
}
}
there is a good article about it in this link: https://medium.com/js-dojo/how-to-deal-with-cors-error-on-vue-cli-3-d78c024ce8d3
Add this to vue.config.js and restart your server after the configuration change.
devServer: {
proxy: {
"/": {
target: "http://localhost:5001",
ws: false,
changeOrigin: true,
logLevel: 'debug'
}
}
Use this in your component.
let url = "/recData";
let payload = {
firstName: "Fred",
lastName: "Flintstone"
}
axios.post(url, payload)
.then(res=>{
console.log(res);
})
.catch(err=>{
console.log(err);
});
I hope it works and I was able to help you.
Related
I have a django application and I have a react native app. I am running the android emulator from android studio.
And now I try to connect the backend with the frontend. I studied the example from: https://reactnative.dev/docs/network
And the example url: https://reactnative.dev/movies.json' works.
I run the native-react app on port: http://192.168.1.69:19000/
And I run the backend on port: http://127.0.0.1:8000/api/movies/
But now I try to connect with my own localhost data. So this is my component:
import { ActivityIndicator, FlatList, Text, View } from "react-native";
import React, { Component } from "react";
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
isLoading: true,
};
}
async getMovies() {
try {
const response = await fetch("http://127.0.0.1:8000/api/movies/", {
method: "GET",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
});
const json = await response.json();
this.setState({ data: json.movies });
} catch (error) {
console.log(error);
} finally {
this.setState({ isLoading: false });
}
}
componentDidMount() {
this.getMovies();
}
render() {
const { data, isLoading } = this.state;
return (
<View style={{ flex: 1, padding: 24 }}>
{isLoading ? (
<ActivityIndicator />
) : (
<FlatList
data={data}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => <Text>{item.title}</Text>}
/>
)}
</View>
);
}
}
this is the data from postman:
[
{
"id": 1,
"title": "Husband",
"description": "Very nice wife cocks the man",
"no_of_ratings": 1,
"avg_rating": 5.0
},
{
"id": 2,
"title": "Nice movie",
"description": "Description ah, niceNICE",
"no_of_ratings": 0,
"avg_rating": 0
}
]
But if I try to run this example. I get this error:
Access to fetch at 'http://127.0.0.1:8000/api/movies/' from origin 'http://localhost:19006' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Question: how to make a connection from native react witht the backend?
Oke, I installed:django.cors.headers and in settings I did all the configuration.
So in django I have this:
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000",
]
and in react native I have this:
useEffect(() => {
fetch("http://127.0.0.1:8000/animalGroups/group/", {
method: "GET",
})
.then((res) => res.json())
.then((jsonres) => setAnimalGroup(jsonres))
.catch((error) => console.error(error));
}, []);
and the native react app is running on:
› Opening exp://192.168.1.69:19000 on MY_ANDROID
So but I still get this error:
Network request failed
at node_modules\whatwg-fetch\dist\fetch.umd.js:null in setTimeout$argument_0
Follow the steps to Set CORS and call your application endpoint directly.
1.) Set the backend endpoint to accept and display data from incoming requests.
i.) first do something like this pip install : pip install django-cors-headers
ii.) in your settings.py file, add the following code snippet to your file
INSTALLED_APPS = [
...
'corsheaders',
...
]
iii.) add CORS middleware to django file
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
...
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware', //<== Add this
]
iv.) add CORS_ORIGIN_ALLOW_ALL = True to settings.py
v.) Endpoint is now accessible to every app.
2.) Make your fetch to be something like this
getMovies = async () => {
var url = 'http://127.0.0.1:8000/api/movies/';
fetch(url, {
method: 'GET',
mode: 'cors',
headers: {
'Content-type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
})
.then(response => response.json())
.then(responseJson => {
setTransaction_details(responseJson);
setLoading(false);
});
};
I have the following techstack
FastApi - backend
React - frontend
and want to implement socketio(not Websockets provided by FastApi). It lacks documentation in both FastApi and Socketio
As needed we are using python-socketio for backend socket server and on react we will be using socket.io-client.
After installation we need to setup a socket server.
Backend Implementation
# socket.py
def handle_connect(sid, environ):
logger.info(f"Socket connected with sid {sid}")
class SocketManager:
def __init__(self, origins: List[str]):
self.server = socketio.AsyncServer(
cors_allowed_origins=origins,
async_mode="asgi",
logger=True,
engineio_logger=True,
)
self.app = socketio.ASGIApp(self.server)
#property
def on(self):
return self.server.on
#property
def send(self):
return self.server.send
def mount_to(self, path: str, app: ASGIApp):
app.mount(path, self.app)
socket_manager = SocketManager(settings.origins)
socket_manager.on("connect", handler=handle_connect)
Double check your cors origins. Also you can add other handlers as well using socket_manager.on.
#main.py
from socket import
app = FastAPI(...)
socket_manager.mount_to("/ws", app)
Frontend Implementation
Basic code for integration is as simple as
import { io } from "socket.io-client";
const socket = io("ws://localhost:8000", {{ path: "/ws/socket.io/", transports: ['websocket', 'polling'] }});
socket.on("connect", () => { console.log("Connected", socket.id) });
socket.on("response", () => { console.log("Response", socket.id) });
socket.on("message", data => { console.log(data) });
For my project i created a context for this as follows
import React, { createContext, useContext, useEffect, useState } from 'react';
import { io } from "socket.io-client";
import { useToastContext } from './ToastContext';
export const SocketContext = createContext()
export const SocketProvider = ({ children, uri, options }) => {
const [socketIo, setSocketIo] = useState()
const { sendToast } = useToastContext();
useEffect(() => {
const socket = io(uri, options);
socket.on("connect", () => { console.log("Connected", socket.id) });
socket.on("response", () => { console.log("Response", socket.id) });
socket.on("message", data => {
sendToast(data)
});
setSocketIo(socket)
}, [])
return (
<SocketContext.Provider value={socketIo}>
{children}
</SocketContext.Provider>
)
}
export const useSocket = () => {
return useContext(SocketContext)
}
Now to finally send a message from your server to client you can do
socket_manager.send("Hello World")
Points worth noting
CORS origin should be exactly same if it is http://localhost:3000 from frontend then it should be http://localhost:3000 and not http://localhost:3000/. Look for the backslash
Also the socketio documentation says transports: ['websocket', 'polling'] is default but when i remove this. It gives me cors error. Documentation might be out of date.
Trying to get json data to front end and have tried a bunch of versions of axios requests but keep getting 404 status code.
This is an example of the front end format:
class App extends Component {
constructor () {
super();
this.state = {
message: ''
};
this.handleClick = this.handleClick.bind(this);
}
handleClick () {
axios.get('./hello')
.then(response => {
this.setState({ message: response.data.text });
})
.catch(error => {
console.log(error);
});
}
render () {
return (
<div className="button-container">
<button className='button' onClick={this.handleClick}>Click Me</button>
<p>{this.state.message}</p>
</div>
)
}
}
and back end routing:
#app.route('/hello')
def hello_world():
return jsonify(text='hello world')
Error message says 'Failed to load resource: the server responded with a status of 404 (Not Found)' or says http://localhost:5003/hello doesn't exist
First check your server, which url and port, your api is exposed
You need to pass complete url to axios constructor otherwise it will send request to same origin/url where your client is hosted, .e.g webapp at localhost:3000.
So your code will be
const SERVER_URL = 'http:localhost:5000'
axios.get(`${SERVER_URL}/hello`)
In my React front end, I call Axios with post method successfully, in my Python Falcon backend parameters are received successfully and token is generated back,
problem is the code in .then or even .catch are never called, here is my front end code:
async submit() {
//var aluser = this.this.state.username;
await axios({
method: "post",
url: "http://127.0.0.1:8000/Login",
headers: {
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
},
params: {
username: this.state.username,
password: this.state.password
}
})
.catch(error => {
console.log(
"here is the error on a post request from the python server ",
error
);
})
.then(res => {
console.log(res);
sessionStorage.setItem("token", res.data[0]);
});
}
Note: the order of .then .catch was switched before, same result.
Thanks in advance
try to use try/catch
const params = new URLSearchParams();
params.append('username', this.state.username);
params.append('password', this.state.password);
async submit() {
//var aluser = this.this.state.username;
try {
const res = await axios({
method: "post",
url: "http://127.0.0.1:8000/Login",
headers: {
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
},
params
})
sessionStorage.setItem("token", res.data[0]);
} catch (err) {
console.log(
"here is the error on a post request from the python server ",
error
);
}
}
If your backend service is only returning a 200 response, axios will not call "then" because you haven't send response data back. I just sent an "OK" response payload back with my 200 status code. "then" was called as expected.
I've been working on a long-polling system. I use flask + mongokit + celery + gevent.
When the process in celery task is done, gevent.event.set() doesn't work. I want help to figure it out. (The reason I use gevent at the same time as celery, is because there is a huge process to deal with in Notification system.)
Here is my sample code.
#server.py
#celery.task()
def doing_task(uid, message):
notification = Notification() # this is a notification Model
notification.add(request.args.get('to'), some_notification)
app.event.set()
app.event.clear()
#app.route('/main')
def main():
return render_template('main.html')
#app.route('/set')
def set():
doing_task.delay(request.args.get('uid'), 'Notify')
return 'OK'
#app.route('/poll')
def poll():
uid = request.args.get('uid')
app.event.wait()
if is_authorized(uid): #uid 1 is a authorized account
return Notification().get(uid)
#main.html
<body>
<button>Click me</button>
</body>
<script>
$('button').click(function(e) {
$.ajax({
'url': '/set',
'data': 'uid=1',
'success': function(data) {
console.log(data);
}
});
e.preventDefault();
});
var poll = function() {
return $.ajax({
'url': '/poll',
'method': 'get',
'async':true,
'dataType': 'json',
'timeout': 10000,
'success': function(data) {
console.log(data);
setTimeout(poll, 50);
},
'error':function (req,sta,er){
setTimeout(poll, 3000);
},
});
};
poll()
</script>
Now, in Flask 0.9 Flask.app_context is added, With Flask.app_context you can get a context of current.
See Application Context.
For example,
from flask import Flask
from celery import Celery
app = Flask(__name__)
celery = Celery(__name__)
#celery.task
def hello():
# Also, you are able to deal with current request as use test_request_context
with app.app_context():
print current_app
with app.test_request_context() as request:
print('Hello {0!r}'.format(request))