React native axios post request network error on Android physical device
( Note: I am a complete beginner in react native and have gone through a lot of reference searching for a solution and nothing helped.) I am using axios with https url for post request and this is my code.
try {
const response = await axios.post(
'https://aaa.bb.com/...................',
{
headers: {
// //Header Defination
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded', // tried application/json
'X-Requested-From': 'MOBILE',
'Authorization': 'Basic ' + loginCredential,
},
},
);
console.log('Success : ' + response);
} catch (error) {
// handle error
console.log(error);
}
I don't need the body part. I have used the same url with data on android native version and it worked fine. But on react-native I am getting "Error: Network Error" as message without any description. Tried using android:usesCleartextTraffic="true" in manifest.
Any help would be grateful. Thank you
See also questions close to this topic
-
Unstable latency - IOS / Android
Rather annoying issue here, I'm developing an extremely latency-critical application (Nothing online all locally hosted servers on the same network), pinging the server IP from any other desktop or laptop either wireless or wired nets a sub 5ms ping however with mobile devices the latency jumps all over going from 100ms to 20ms to 400ms with absolutely no pattern.
I've ruled this out as a hardware problem (Several people experiencing it on different networks with different devices)
I did read about 802.11g compliance and also some fast wifi root override on android but I was wondering if anyone has experienced this or even has a solution to it?
-
Undismissible dialog in Flutter
What I want to achieve is to make dialog that's impossible to dismiss by clicking back button in android.
I know about
barrierDismissible
property ofshowDialog
method, but it only does what the name suggests. With it set tofalse
and clicking on back button the dialog still disappears.I also tried to wrap my code in
WillPopScope
to intercept back button click, butonWillPop
is never called if the dialog is shown. Maybe I messed up withcontext
or something, or there's another way to achieve this behavior? Any help is appreciated.I've modified the default counter app a bit to show at which stage my research is currently
void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; bool _isLocationWarningActive = false; void _incrementCounter() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { return WillPopScope( onWillPop: () async { // this is never called if the dialog is shown if (_isLocationWarningActive) return true; return false; }, child: Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: LocationChecker( isLocationWarningActive: _isLocationWarningActive, setIsLocationWarningActive: (value) { setState(() { _isLocationWarningActive = value; }); }, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.headline4, ), ], ), ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ), ); } } class LocationChecker extends StatefulWidget { final bool isLocationWarningActive; final Function(bool) setIsLocationWarningActive; final Widget child; const LocationChecker({Key key, this.setIsLocationWarningActive, this.isLocationWarningActive, this.child}) : super(key: key); @override _LocationCheckerState createState() => _LocationCheckerState(); } class _LocationCheckerState extends State<LocationChecker> with WidgetsBindingObserver { @override void initState() { WidgetsBinding.instance.addObserver(this); super.initState(); } @override void dispose() { WidgetsBinding.instance.removeObserver(this); super.dispose(); } @override void didChangeAppLifecycleState(AppLifecycleState state) { print("state: $state"); if (state == AppLifecycleState.resumed && !_isCheckingLocation) { _showLocationSettingsAlertIfNeeded(); } } bool _isCheckingLocation = false; Future _showLocationSettingsAlertIfNeeded() async { if (!mounted) return; _isCheckingLocation = true; if (await checkLocationPermission) { if (widget.isLocationWarningActive) { widget.setIsLocationWarningActive(false); _isCheckingLocation = false; Navigator.of(context).pop(true); } } else if (!widget.isLocationWarningActive) { print("should show notification"); widget.setIsLocationWarningActive(true); await showDialog( context: context, barrierDismissible: false, builder: (BuildContext context) => OneActionDialog( title: "Location Settings", child: Text("Click OK to goto settings"), btnTitle: "OK", action: () { widget.setIsLocationWarningActive(false); _isCheckingLocation = false; SystemSetting.goto(SettingTarget.LOCATION); Navigator.of(context).pop(true); }, ), ); } } @override Widget build(BuildContext context) { return Container( child: widget.child, ); } } Future<bool> get checkLocationPermission async { ServiceStatus serviceStatus = await LocationPermissions().checkServiceStatus(); if (serviceStatus != ServiceStatus.enabled) return false; final access = await LocationPermissions().checkPermissionStatus(); switch (access) { case PermissionStatus.unknown: case PermissionStatus.denied: case PermissionStatus.restricted: final permission = await LocationPermissions().requestPermissions( permissionLevel: LocationPermissionLevel.locationAlways, ); if (permission == PermissionStatus.granted) { return true; } else { return false; } break; case PermissionStatus.granted: return true; break; default: return false; break; } }
-
What exactly is full screen intent in android?
I've been looking up what full screen intent is, but I couldn't get a hold of what it exactly is. There are some partial code examples, but rarely I see any examples in a visible form. I got confused as I looked up what full screen intent is referring to.
From what I saw, it seems like it pops a notification bar, but not on the status bar. When the user presses the notification bar it moves on to full screen.
However, I got confused as I read this question. FullScreenIntent only appears if I clear the notification This question states that full screen intent appears when he clears the notification bar. What is full screen intent referring to? Videos in youtube seem to tell that full screen intent is about popping up a notification bar and going to a full screen activity by clicking it, but when I read the question above, I get a feeling that it's something that is separate from notification bar.
What exactly is full screen intent?
-
How to keep scroll position after selecting an item react native flatlist
Whenever I have a long list and I scroll down to select an item, after selection, it'll jump back up to the top. How can I make it so after selection, the screen does not change?
When trying to look more into this, I get search results for this problem but when adding new items or how to implement infinite scroll which is not the situation here.
I've tried assigning a ref to the flatlist and after the action trigger by selecting an item, scroll to the last saved position, but that doesn't change anything.
<FlatList contentContainerStyle={{paddingBottom: 10}} data={stores as Stores[]} renderItem={({item}): JSX.Element => ( <TouchableOpacity onPress={(): void => action(item)}> <Text>{item}</Text> </TouchableOpacity> )} ItemSeparatorComponent={(): JSX.Element => <ItemSeparator />} keyExtractor={(item): string => item.id.toString()} ListHeaderComponent={ <ListHeader /> } />
-
How to use laravel permissions in react front end?
I have set the ACL of the laravel application . I have developed role each role has specific permissions. In laravel blade it is very easy check permissions like this
@if(auth()->user()->hasPermission('customers','view')) <li class="kt-menu__item {{ Request::segment(1) == 'customers' ? 'kt-menu__item--active' : '' }}" aria-haspopup="true"> <a href="{{route('customers.index')}}" class="kt-menu__link "> <span class="kt-menu__link-icon"><i class="fa fa-users" aria-hidden="true"></i> </span> <span class="kt-menu__link-text">Customers</span> </a> </li> @endif
How i can do this in react js ?
-
native-base Accordion Error with indexOf is not a function
I am new to React Native, so I apologize if this is a stupid question, but I am getting an error using the Accordion component from native-base. I gives me a message of "e.state.selected.indexOf is not a function".
I have the example code from the native-base docs pasted into a snack here to show the problem. Here is that code, it is pretty simple:
import React, { Component } from "react"; import { Container, Header, Content, Accordion, Text } from "native-base"; const dataArray = [ { title: "First Element", content: "Lorem ipsum dolor sit amet" }, { title: "Second Element", content: "Lorem ipsum dolor sit amet" }, { title: "Third Element", content: "Lorem ipsum dolor sit amet" } ]; export default class AccordionExample extends Component { render() { return ( <Container> <Header /> <Content padder> <Accordion dataArray={dataArray} expanded={0}/> </Content> </Container> ); } }
-
Axios: onUploadProgress event gets only triggered after video is uploaded completely
I am trying to track the progress of video upload and accordingly display it to the user.
This is the axios request that uploads the video.const config = { onUploadProgress: function (progressEvent) { var percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total ); console.group("profileActions.uploadProfileVideoURL"); console.log("progressEvent.loaded: ", progressEvent.loaded); console.log("progressEvent.total: ", progressEvent.total); console.log("percentCompleted: ", percentCompleted); console.groupEnd(); }, }; axios .post("/api/profile/uploadProfileVideoURL", videoData, config)
The problem is that it only gets triggered when video is completely uploaded.
I have found this discussed in this Github Axios Issue:Only 100% can be fired in case your upload files are too small, or download/upload speed is too fast. Try to upload 10mb file maybe.
So I tried uploading a 100Mb video, and the event still gets triggered at then end of the upload.
Any idea why is this happening?
And can I fine-tune axios for the event to get triggered at certain progress values? -
HTML Form strangely POSTING before I even submit
I have this HTML form:
<form id="myForm" type="POST" onclick="addTodo()"> <fieldset> <legend>Company Information</legend> <label for="shippingName">Company Name:</label> <input type="text" name="company" id="company" /><br /> </fieldset> <br /> <input type="hidden" name="uniqueid" id="uniqueid"> <input type="submit" value="Submit" id="form-submit" /> </form>
As soon as I click the field to type in a value, my Airtable DB creates row, when I finally submit, I have 2 possibly 3 rows.
Here's my js code:
function addTodo() { dddd = document.getElementById('company').value app_id = "app123456789" app_key = "key123456789" table_id = "Table123456789" let data = { "records": [ { "fields": { "Notes": "Notes", "Company Name": dddd } } ] }; let axiosConfig = { headers: { 'Authorization': "Bearer " + app_key, 'Content-Type': "application/json" } }; axios.post("https://api.airtable.com/v0/" + app_id + "/" + table_id, data, axiosConfig) .then(resp => console.log(resp)) .catch(error => console.log(error)) };
What am I doing wrong?
-
I wanted to delete the user account on frontend using id on React using axios
import React from "react"; import styles from "./Settings.module.css"; import axios from "axios"; const Settings = (e) => { const deleteAccount = async (info) => { const config = { headers: { 'Authorization': "authorizationToken" } }; try { const result = await axios.delete( "http://localhost:7000/user/deleteAccount/:id",
import React from "react"; import styles from "./Settings.module.css"; import axios from "axios"; const Settings = (e) => { const deleteAccount = async (info) => { const config = { headers: { 'Authorization': "authorizationToken" } }; try { const result = await axios.delete( "http://localhost:7000/user/deleteAccount/:id", info, config ); console.log(result); // setLoggedIn(true) } catch (error) { console.log(error); } }; const handleDeleteSubmit = async (e) => { e.preventDefault(); const userDelete = new userDelete(e.target); // const dataDelete= { // _id:userDelete.remove("email") // } }; try { deleteAccount(); } catch (error) {} return ( <div className={styles.containersetting}> {" "} Settings <div className={styles.deletecontainer}> <p> Are you sure you wanted to delete your account? If you choose to delete your account, you have to register again. </p> <button onClick={handleDeleteSubmit} className={styles.deletecontainer1} > Delete Account </button> </div> </div> ); }; export default Settings;
info, config ); console.log(result); } catch (error) { console.log(error); } }; const handleDeleteSubmit = async (e) => { e.preventDefault(); const userDelete = new userDelete(e.target); }; try { deleteAccount(); } catch (error) {} return ( <div className={styles.containersetting}> {" "} Settings <div className={styles.deletecontainer}> <p> Are you sure you wanted to delete your account? If you choose to delete your account, you have to register again. </p> <button onClick={handleDeleteSubmit} className={styles.deletecontainer1} > Delete Account </button> </div> </div> ); }; ' export default Settings;
========================================= Here is my middleware const jwt = require("jsonwebtoken") const User = require("../Models/UserModel")
module.exports = async(request,response,next)=>{
const token = request.cookies.jwt console.log('authenticate ',token);
if(!token){ return response.status(400).json({msg: 'No Token authorization denied!!'}) } try{ const decode = await jwt.verify(token, process.env.SECRET) console.log('decode:', decode); request.id = decode.id const currentUser = await User.findById(decode.id) if(!currentUser){ return response.status(400).json({msg: 'The User with the current token is no longer exist'}) } request.id = currentUser.id console.log(request.user); next() } catch(error){ console.log(error); return response.status(400).json({msg: 'Token is not valid'}) }
}
======================
My error is authenticate undefined