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);
});
};
Related
The code snippet is simply about performing a post request to a machine learning model endpoint and logging out the response if successful.
import urllib.request
import json
import os
import ssl
def allowSelfSignedHttps(allowed):
# bypass the server certificate verification on client side
if allowed and not os.environ.get('PYTHONHTTPSVERIFY', '') and getattr(ssl, '_create_unverified_context', None):
ssl._create_default_https_context = ssl._create_unverified_context
allowSelfSignedHttps(True) # this line is needed if you use self-signed certificate in your scoring service.
# Request data goes here
# The example below assumes JSON formatting which may be updated
# depending on the format your endpoint expects.
# More information can be found here:
# https://learn.microsoft.com/azure/machine-learning/how-to-deploy-advanced-entry-script
data = {
"Inputs": {
"data": [
{
"test_date": "2000-01-01T00:00:00.000Z",
"cough": false,
"fever": 0,
"sore_throat": false,
"shortness_of_breath": 0,
"head_ache": 0,
"age_60_and_above": "example_value",
"gender": "example_value"
}
]
},
"GlobalParameters": {
"method": "predict"
}
}
body = str.encode(json.dumps(data))
url = 'http://8daf0a82-3a30-4581-96c3-5d4374473502.southafricanorth.azurecontainer.io/score'
api_key = '' # Replace this with the API key for the web service
# The azureml-model-deployment header will force the request to go to a specific deployment.
# Remove this header to have the request observe the endpoint traffic rules
headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}
req = urllib.request.Request(url, body, headers)
try:
response = urllib.request.urlopen(req)
result = response.read()
print(result)
except urllib.error.HTTPError as error:
print("The request failed with status code: " + str(error.code))
# Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
print(error.info())
print(error.read().decode("utf8", 'ignore'))
I have tried this, but I keep getting
"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://8daf0a82-3a30-4581-96c3-5d4374473502.southafricanorth.azurecontainer.io/score. (Reason: CORS request did not succeed). Status code: (null)."
function predict() {
axios
.post(
"http://8daf0a82-3a30-4581-96c3-5d4374473502.southafricanorth.azurecontainer.io/score",
{
Inputs: {
data: [
{
cough: S1Val.value,
fever: S2Val.value,
sore_throat: S3Val.value,
shortness_of_breath: S4Val.value,
head_ache: S5Val.value,
age_60_and_above: a1.value,
gender: a2.value,
},
],
},
GlobalParameters: {
method: "predict",
},
},
{
headers: {
"Access-Control-Allow-Orgin": "*",
"Content-Type": "application/json",
},
}
)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
}
Also note that this endpoint doesn't require any authentication that's why I didn't append an API key to the Bearer when performing the request.
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.
i am working on a django application currently deployed on azure app service.i includes generation of report in docx. format. in some scenerios i takes upto 5-6 minutes. at first i encountered activity timeout after 70 sec which i solved by using applicationHost.xdt to configure activitytimeout and request timeout.
then another timeout happened after 230 sec almost. which according to my knowledge is due to load balancer. i understand it is not configurable in app service.. do i tried another technique which basically does is that it keeps pinging backend from client after every 180 sec. but the problem didn't go away. pasting detailed code below.
Thanks in advance
function pinger(stop)
{
if (status == true)
{
return;
}
else
{
$.ajax({
async : false,
url:"{% url 'DummyUrl' %}",
type: "GET",
data: {},
beforeSend:function()
{
console.log('starting dummy')
},
success:function(response){
console.log('success dummy')
console.log(response.data)
},
complete:function(){},
error:function (xhr, textStatus, thrownError){}
});
return;
}
}
function generate_report()
{
var status = false;
$.ajax({
async : true,
url:"{% url 'GenerateReport' %}",
headers: { "X-CSRFToken": '{{csrf_token}}' },
type: "POST",
data: {},
beforeSend:function()
{
console.log('starting');
console.log('readonly');
},
success:function(response){
if (response.data.toString().includes('.docx'))
{
console.log(response);
var url_mask = "{% url 'download report' filename=12345 %}".replace(/12345/, response.data.toString());
console.log('document generated successfully here is the link');
status = true;
show_download_link(url_mask);
}
else{ console.log(response)}
},
complete:function(){
console.log('completed')
},
error:function (xhr, textStatus, thrownError){
Error_Link();
console.log('error+')
}
});
// pinger(stop)
setTimeout(function(){ pinger(status); }, 180000);
// setInterval(pinger(stop) , 120000);
}
$("#generate_report_form").on('submit', function(event){
event.preventDefault();
generate_report();
});
the code above calls two APIs simultaneously one for report generation and one for keeping connection alive. but timeout still happens. Please help....
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 have a Node JS application. I want to send an image from the Node JS application to a REST API which is written in Python. The key and the inputs needed by the Python REST API are as follows
My problem is that I am able to POST a simple 'Hello World' string with the code I have written and get a response. However, when I try to send an image something goes wrong and I get no response.
var http = require('http');
var querystring = require('querystring');
// This is some dummy string data
var postData = querystring.stringify({
msg: 'hello world'
});
var fs = require('fs')
, path = require('path')
, certFile = path.resolve(__dirname, 'ssl/client.crt')
, keyFile = path.resolve(__dirname, 'ssl/client.key')
, caFile = path.resolve(__dirname, 'ssl/ca.cert.pem')
, request = require('request');
// I want to send an image from one server to another. What changes should I make to the options below for POSTing image data
var options = {
hostname: '127.0.0.1',
port: 8888,
path : '/predict',
//image: fs.createReadStream('car.jpg'), //Should I give something like this??
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
'Content-Length': postData.length
}
};
var req = http.request(options, function (res) {
console.log('STATUS:', res.statusCode);
console.log('HEADERS:', JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY:', chunk);
});
res.on('end', function () {
console.log('No more data in response.');
});
});
req.on('error', function (e) {
console.log('Problem with request:', e.message);
});
req.write(postData);
req.end();
Please let me know what changes I have to make to this code to post an image.I read about the use of multer package. However, the examples that I came across were using JS on both ends. Since for me, I have a Python REST API , I cannot use that. PLease help since I have been struggling with it for some time now.
Edit 1: Based on #Jana's suggestion, I added the multipart within the options and tried, where image is the key and the value is fs.createReadStream('car.jpg') . However, at the python end, it does not get the 'image' key because of which I get a False response. What am I missing?
var options = {
hostname: '127.0.0.1',
port: 8888,
path : '/predict',
//image: fs.createReadStream('car.jpg'), //Should I give something like this??
multipart: [
{
'content-type': 'application/json',
body: JSON.stringify({'image': fs.createReadStream('car.jpg') })
}
],
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
//'Content-Length': postImageData.length
}
};
Check this,
`request({
method: 'POST',
uri: 'http://127.0.0.1:8888/predict',
multipart: [{
'content-type': 'application/json',
body: JSON.stringify({
"key": "value"
})
},
{
body: fs.createReadStream('car.jpg')
}
],
},
function(error, response, body) {
if (error) {
return console.error('upload failed:', error);
}
console.log('Upload successful! Server responded with:', body);
})`
And also you can get the best examples from its own documentation Request - Simplified HTTP client