Django, React-Native Connection Network Request Failed - django

I'm working on a react-native-based mobile application and doing some operations with python in the background. I wanted to do both these transactions and connect to the database via Django rest api. But I get connection error.
I have used other rest-api and tried it. I also tried the rest api on the postman and it worked smoothly.
I tried everything, but I couldn't find a solution.
local rest url: http://localhost:8000/api/venues/
and fetch code:
componentDidMount() {
return fetch('http://localhost:8000/api/venues/?format=json')
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({
isLoading: false,
dataSource: responseJson,
}, function(){
});
})
.catch((error) =>{
console.error(error);
});
}
also my django setting:

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = [
'http://localhost:3030',
]
CORS_ORIGIN_REGEX_WHITELIST = [
'http://localhost:3030',
]
add these configurations after adding cors as middleware (change to your port number)

https://stackoverflow.com/a/69186898/12497001 provides a very good answer!
As mentioned in the Android Studio documentation, emulators use a special address network (https://developer.android.com/studio/run/emulator-networking.html).
To address requests to your own machine, you can use the address http://10.0.2.2

Related

(React Native and Django) TypeError: Network request failed

I'm developing a mobile app with the concept of using react-native as front end and Django as back-end. I'm actually following this series of tutorials: Javascript Fetch - Communicating between a ReactNative App and Django REST API but when I got to the part where I have to use a fetch method I am getting a TypeError: Network request failed.
Here is a snippet of my code:
const [ domain, setDomain ] = useState("http://10.0.2.2:8000")
function initAppSettings(){
console.log(domain)
fetch(`$(domain)/api/v1.0/app/settings`, {
method: 'GET',
})
.then (result => {
if (result.ok) {
return result.json()
} else {
throw result.json()
}
})
.then (JSON => {
console.log(JSON)
})
.catch (error => {
console.log(error)
})
}
useEffect(() => {
initAppSettings()
}, [])
I have already tried editing the AndroidManifest.xml by adding
android:usesCleartextTraffic="true". I also tried using my own ipv4 address in my Django runserver but still failed to access it.
I have the same question as this but the answer here do not solve my issue.

django-graphql-jwt JWT_COOKIE_SAMESITE not working

I'm using Django GraphQL JWT Library and Django GraphQL Auth
I keep getting this error
google chrome error
With this react code (trimmed for relevancy) on both http://localhost:3000/ and https://localhost:3000/
const [login] = useMutation(LOGIN_MUTATION, {
variables: {
email: email,
password: password
},
onCompleted: ({ tokenAuth }) => {
if (tokenAuth.success) {
setToken(tokenAuth.token);
}
}
});
Now when I run this mutation from the graphiql page it works and I end up with a JWT cookie but not on the react site
mutation {
tokenAuth(
email:"********"
password:"*********"
){
token
refreshToken
success
errors
}
}
This doesn't work
GRAPHQL_JWT = {
"JWT_COOKIE_SAMESITE": 'None',
"JWT_ALLOW_ARGUMENT": True
}
Adding these didn't work
"CSRF_COOKIE_SECURE": True,
"SESSION_COOKIE_SECURE": True,
"CSRF_COOKIE_SAMESITE": 'None',
"SESSION_COOKIE_SAMESITE": 'None',
"JWT_VERIFY_EXPIRATION": True,
Adding these to django settings also didn't work
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_SAMESITE = 'None'
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_SAMESITE = 'None'
I've been stuck on this for about 3 days now and am about ready to throw myself in a river and go build tables. Please help.
Support for the JWT_COOKIE_SAMESITE setting was added for django-graphql-jwt on version v0.3.2. You can check the releases here releases. While the current django-graphql-auth package relies on django-graphql-jwt v0.3.0. Updating your requirements will solve this issue.
so the issue is you are using
"JWT_COOKIE_SAMESITE": 'None'
which only works if
"JWT_COOKIE_SECURE": True
and JWT_COOKIE_SECURE means the cookie will only be sent over HTTPS connection and this won't work with HTTP connection.
considering you have HTTP and the backend is using the same domain as frontend then all you need to add is
"JWT_COOKIE_SAMESITE": 'Lax'
"JWT_COOKIE_SECURE": False
cookies are default into “SameSite=Lax” which means cookies are only set when the domain in the URL of the browser matches the domain of the cookie

CSRF_Token in POST method using Vue.js and Django Rest Framework

I'm trying to send a POST request from a Vue.js template to my API created with Django.
When sending I get a 403 CSRF token missing or incorrect error. Since I separated the front and the back, I don't have a view with {csrf_token} on the Django side.
How do I send my form?
I tried some exemples on the web using cookies but i'm beginners and need more explaination about the POST subject and CSRF
I have a Djano View (and urls associated) juste like this :
def get_csrf_token(request):
token = get_token(request)
return JsonResponse({'token': token})
Whe i'm requesting the url, obtained the JSON with the token.
And on the Front side i'm using this method to get the Token :
getToken: function() {
this.loading = true;
this.$http.get('/qualite/get-token/')
.then((response) => {
this.token =response.data;
this.loading = false;
})
.catch((err) => {
this.loading = false;
console.log(err);
})
},
addNc: function() {
let headers = {
'Content-Type': 'application/json;charset=utf-8'
};
if(this.token !== '') {
headers['HTTP_X-XSRF-TOKEN'] = this.token
}
this.loading = true;
this.$http.post('/qualite/api/nc/',this.newNc, {headers: headers})
.then((response) => {
this.loading = false;
})
.catch((err) => {
this.loading = false;
console.log(err)
})
},
For the CSRF you get by default after user login aside with the session, if you're using SessionAuthentication (It's the default authentication used in DRF).
You have to send it with each request in the header, you can refer the this link to know more about the header sent, as it's name is changed and can be configured.
Note also that in the settings you have to make sure that CSRF_COOKIE_HTTPONLY is set to False (which is the default), to be able to read it from the client side JS.
Another path would be removing CSRF enforcement per requests (But it's highly not recommended for security concerns), you can find more about this in the answer here.
Use a Token-based authentification.
Same issue i was encountered with,
the problem was, i had used Class based view and at the time of registered the url i forget to mention as_view() with class Name.
ex:- class PostData(APIView)
before :- path('post_data', PostData)
after correction:- path('post_data', PostData.as_view())

PWA offline service worker settings

I am building a simple Progressive Web Application with Python Django and django-pwa package. I have set up everything but offline functionality is not working. At this point, service workers (SW) are installed and dev tools recognize application as PWA. But when I check "offline" in devtools->Application and reload the web page there is a "No internet connection" error.
Here are my SW settings:
var staticCacheName = 'djangopwa-v1';
var filesToCache = [
'/',
'/x_offline/',
'/static/x_django_pwa/images/my_app_icon.jpg',
'/media/images/bfly1.2e16d0ba.fill-320x240.jpg',
];
// Cache on install
self.addEventListener("install", event => {
this.skipWaiting();
event.waitUntil(
caches.open(staticCacheName)
.then(cache => {
return cache.addAll(filesToCache);
})
)
});
// Clear cache on activate
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames
.filter(cacheName => (cacheName.startsWith("djangopwa-v1")))
.filter(cacheName => (cacheName !== staticCacheName))
.map(cacheName => caches.delete(cacheName))
);
})
);
});
// Serve from Cache
self.addEventListener("fetch", event => {
event.respondWith(
caches.match(event.request)
.then(response => {
return response || fetch(event.request);
})
.catch(() => {
return caches.match('x_offline');
})
)
});
Listed settings are almost the same as default one from django-pwa repo
When I load the page for the first time I see that requests are also made for the urls listed in SW and all of them have status 200. In the cache storage I see cache with paths set in SW. So I don't understand what I do wrong.
Not sure if this additional info is useful, but: when I set SW to offline and reload the web page the cache storage is empty.
The issue is in the settings that django-pwa repo provided.
They accidentally added sign , at the end of the scope variable and so if you copy settings you copy with incorrect scope setting (PWA_APP_SCOPE = '/',) and it brakes offline mode. I am going to contact with repo admins so that to fix the issue for the next users.

Axios GET request to server - not local host

I was wondering if someone could bring some light on how GET request paths work. I am not skilled in networking so am a bit lost here.
I have a Flask app running on PythonAnywhere... I built a small app with Vue and am using Axios for send GET request to my API on server. I however found out that when I run my app on PythonAnywhere server i will get response only when I also run the flask app on my local machine. I suspect it is due to me trying to send the request to http://localhost:5000/api/random2. Is that true? What do I have to replace it with to send the request to my PythonAnywhere app?
getResults () {
const path = `http://localhost:5000/api/random2`
axios.get(path, {
params: {
p_a: this.p_a,
R_eH: this.R_eH,
a: this.a,
b: this.b
}
})
.then(response => {this.result = response.data})
.catch(error => {
console.log(error)
})
}
},
Thank you,
Jakub