How to access Django local server data with React-native? - javascript

I build a Django API using django rest framework.
And a want to access the json response data of the api in my react-native app.
But a get an error (Network request failed)
DJANGO RESPONSE
REACT-NATIVE
ERROR
Network request failed
node_modules/whatwg-fetch/dist/fetch.umd.js:505:17 in setTimeout$argument_0
node_modules/react-native/Libraries/Core/Timers/JSTimers.js:135:14 in _callTimer
node_modules/react-native/Libraries/Core/Timers/JSTimers.js:387:16 in callTimers
node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:425:19 in __callFunction
node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:112:6 in __guard$argument_0
node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:373:10 in __guard
node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:111:4 in callFunctionReturnFlushedQueue
[native code]:null in callFunctionReturnFlushedQueue

Please consider take the following suggestions:
activate developer mode on your device and than turn on the "USB Debugging" mode.
Plug your device into a USB port on your pc
Add this line into your package.json file inside the scripts object:
"android-dev": "adb reverse tcp:8081 tcp:8081"
Check if CORS is configured in your settings.py Django project file and make sure to allow all hosts to access the project (of specify the hosts if that's important to your tests).
INSTALLED_APPS = [
...
'rest_framework',
'corsheaders',
...
]
MIDDLEWARE = [
...
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
CORS_ORIGIN_ALLOW_ALL = True
ALLOWED_HOSTS = ['*']
Check your local ip (usually starts with 192.168...). Do this by running ipconfig on windows or ifconfig on linux.
Make sure you are running your Django project with the same IP as your local network. For exemple, my local ip is 192.168.15.2, so I run python manage.py runserver 192.168.15.2:8000. In my case I like to use Pycharm, so I configure it in the server settings
And for the last step, use that same IP in your requests adding the "Access-Control-Allow-Origin":'*' in the request header. So it would be something like this:
Note that I use axios for sending requests, but you can check how add the headers in your request using fetch here.
I wish you the best. This is really a annoying problem that I took some time to figure it out.

Related

Build succeeded for heroku app but running into "Application Error"

When I checked the Heroku build logs, it showed this:
The requested API endpoint was not found. Are you using the right HTTP verb (i.e. GET vs. POST), and did you specify your intended version with the Accept header?
My app runs on React framework for front end, and I use the Firebase realtime database for my backend. The app runs fine on my local server but when I try to deploy on to Heroku I run into this error.
My guess is that you didn't set the environment variables, thus the base url for your request might be invalid. You can set them in Settings tab of your heroku application, under the Config Vars section.

Device Orientation API not working with local webserver

While working with the Device Orientation API I noticed something strange.
The following online demo works perfectly (except for "compassneedscalibration"): https://www.audero.it/demo/device-orientation-api-demo.html
But when I clone the Soucecode locally and provide the Web page via a local Web server* the API seems to not be available anymore. Although using the same browser tab. Also no Messages, warnings or errors appear in the JavaScript console.
The Web page states:
deviceorientation event not supported
devicemotion event not supported
compassneedscalibration event not supported
Am I doing something wrong? Or is this an intended behavior or a bug?
I will need to provide my web app by a local web server.
I am using "Chrome 79.0.3945.93" on "Android 7.1.1;VNS-L21 Build/NMF26V"
*) python3 -m http.server
I found out that you need to provide the wep page via an Encrypted HTTPS connection on order to access the Device Orientation API and also some mediaDevices.
A simple way of providing HTTPS pages during development (not production) is this simple python webserver:
#!/usr/bin/env python3
# Based on http://www.piware.de/2011/01/creating-an-https-server-in-python/
# generate server.xml with the following command:
# openssl req -new -x509 -keyout key.pem -out server.pem -days 365 -nodes
# run as follows:
# python3 simple-https-server.py
# then in your browser, visit:
# https://localhost:4443
import http.server
import ssl
import os
directory_of_script = os.path.dirname(os.path.abspath(__file__))
#server_address = ('localhost', 4443)
server_address = ('', 4443)
httpd = http.server.HTTPServer(server_address, http.server.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket(httpd.socket,
server_side=True,
certfile=os.path.join(directory_of_script, "server.pem") ,
keyfile=os.path.join(directory_of_script, "key.pem"),
ssl_version=ssl.PROTOCOL_TLS)
httpd.serve_forever()

ReactJS could not proxy request from localhost:3000 to localhost:3003

I am writing a SPA using create-react-app and am using an expressjs server as my backend. For development I run my frontend test server on port 3000 and my backend expressjs test server on 3003.
I make many API calls client side using Axios so for development convenience I have defined proxy: "http://localhost:3003" in my package.json
This works fine on my laptop, but when running on my workstation I constantly get the error when accessing my app:
Proxy error: Could not proxy request /sockjs-node/487/wrst1bub/websocket from localhost:3000 to http://localhost:3003/. See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNRESET).
I have no idea where this is coming from and I do not use sockjs in any capacity as far as I know. This is a console error and it does not crash my app but it is very annoying and I would like to get rid of it. Any help is greatly appreciated.
In my case, I was using Firefox and for some reasons, it gives me the same error. I tried to use Chrome and it worked!

Cordova Angular Get to Web Api Connection Refused

I am using Visual Studio 2013 Update 4 and I have a web api project setup to receive get requests that returns an array. For the client app I have setup cordova and am emulating an android angular app using ng-resource to call the web api get. Everytime I call the GET I get a ripple.js error that says connection refused. I get the connection refused even if I try with a real android device as well. Here is the error when using the ripple emulator
OPTIONS http://****:4400/ripple/xhr_proxy?tinyhippos_apikey=ABC&tinyhippos_rur…Fget%3D%257B%2522method%2522%3A%2522GET%2522%2C%2522array%2522%3Atrue%257D net::ERR_CONNECTION_REFUSED
I was sure to enable cors on the web api 2 server since the cordova and web api projects are different port numbers on the same local host. I proved not only the cors functionality but also the code by creating an exact replica of the cordova angular app with just angular web page. I also tried with postman and both get json responses correctly. It is only the cordova android app that is giving me the connection refused. Any help would be greatly appreciated!
Here is what the angular get looks like
app.factory('mrMaintService', function ($resource) {
return $resource('http://localhost:15528/api/requests', {
get: { method: 'GET', array: true }
});
});
This shows I am allowing all domains on the web api project:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
The solution was to disable cross domain proxies from the drop down right in the emulator. Easy mistake to make if you aren't familiar with the ripple emulator.
The answer as it pertains to issues with accessing http://localhost (which is the same thing as 127.0.0.1) can be found here: http://developer.android.com/tools/devices/emulator.html - which says:
"Also note that the address 127.0.0.1 on your development machine corresponds to the emulator's own loopback interface. If you want to access services running on your development machine's loopback interface (a.k.a. 127.0.0.1 on your machine), you should use the special address 10.0.2.2 instead."
So, instead of using http://localhost use http://10.0.2.2 and then append whatever port you're using. Example: http://localhost:8001 can be access at http://10.0.2.2:8001

Node.js on Azure Worker Role w/ SSL results in ERR_SSL_PROTOCOL_ERROR

I have a WorkerRole configured to start node.exe via the Runtime/EntryPoint/ProgramEntryPoint element in the csdef and have a HttpsIn EndPoint configured for https on port 443 w/ a valid certificate. I'm also setting the PORT environment variable in Runtime/Environment which is used by node to listen on for incoming requests.
When I start the service (either in local dev fabric or in Azure) and try to hit the service I get the following error:
SSL connection error
Unable to make a secure connection to the server. This may be a problem with the server, or it may be requiring a client authentication certificate that you don't have.
Error 107 (net::ERR_SSL_PROTOCOL_ERROR): SSL protocol error.
I have verified that node.exe is indeed started when the service starts, and if I look up the local port in the Compute Emulator, usually something like:
http://localhost:444
I am able to successfully hit node directly with that using my browser. I am also able to hit node through Azure when SSL is not configured.
What am I missing? Thanks!
The issue was that I was using the http module instead of the https module when starting the web server in Node. Works once I started the https server using the ssl certificate.
I was following a guide for SSL w/ Node in a WebRole, which requires a different set up than SSL w/ Node in WorkerRole.

Categories