Making Request from Localhost:3000 says NETWORK FAIL to React Native Project - javascript

I had watched a series of tutorials online and had followed lot of steps. I had to change my IP address to my machine IP, but yet network error. even, I had to change it to 127.0.0.1. Am just so tired, I need help badly. I am using a project on the PHPMyAdmin database, which I use to fetch the result using express and node MySQL. I did all I could I even used USB tethering, hotspot, and all but none seems to work
const GetUserData =()=>{
axios.get("http://127.0.0.1:3000/users").then(
(response)=>{
console.log(response.data);
}).catch(err =>{
console.log(err);
})
};
useEffect(() => {
GetUserData()
},[])

Can you add the error message, please? If you face CORS you can fix it by:
var cors = require('cors')
var app = express()
app.use(cors())

Your machine has multiple IP addresses, even with one network device.
Of them:
127.0.0.1 - local IP address. It is not on any network device, and it should not be there.
192.168.x.y - network IP address. It is configured on the network device (manually or automatically).
You don't need to install 127.0.0.1 on a network device. 127.0.0.1 is already your machine, even without any network devices.
Also, to be able to make requests to 127.0.0.1:3000, some service must already listen on this port.

Related

Problem in communicating with Binance exchange in NodeJS web socket

When I execute the following piece of code in the app.js file
const WebSocket = require('ws');
const ws = new WebSocket('wss://stream.binance.com:9443/ws/!miniTicker#arr');
ws.on('message', function (data){
//const result = JSON.parse(data);
console.log(data);
});
I get the following error and I cannot receive data.
10.10.34.34 (what your DNS server resolved stream.binance.com to) is a local IP address! You are not even reaching Binance. It's probably a captive portal or some firewall.
Open that IP address in the browser and check whether you get some sort of web interface that gives you a clue about what is blocking your request. You can also try changing your DNS server to Google (8.8.8.8) or some other public DNS server instead of relying on your router.
Update:
In your comment you mentioned your DNS server is 178.22.122.100 (i.e., shecan.ir). If I try to resolve the domain with that server, I also get nonsensical results (10.10.34.34 and d0::11). According to this book, this is part of Iranian censorship, and your ISP would handle this IP address to show a page about this domain being blocked if you'd open it in a browser.
So, an alternative public DNS server without censorship such as 8.8.8.8, 1.1.1.1 or 9.9.9.9 should help. If this doesn't work then those DNS servers are also blocked by your ISP and you would need to use a VPN or other means of bypassing government censorship.

MQTT TLS connection

I would like to connect a test MQTT-Client to my Node.js application as a MQTT-Broker. I am using the aedes library from moscajs
My MQTT-Client is the tool "MQTT-Explorer" and here is my Node.js application:
const fs = require('fs');
const aedes = require('aedes')();
const options = {
key: fs.readFileSync('certs/server_key.pem'),
cert: fs.readFileSync('certs/server_cert.pem'),
};
// const server = require('net').createServer(aedes.handle);
const server = require('tls').createServer(options, aedes.handle);
const PORT = 8881;
server.listen(PORT, () => {
console.log(`server is up and running: PORT [${PORT}] - ID [${aedes.id}]`);
});
I can connect without any problems to PORT=1881 with const server = require('net').createServer(aedes.handle) and I also can connect to PORT=8881 with const server = require('tls').createServer(options, aedes.handle)
With the Tool xca-2.4.0.msi XCA 2.4.0 I have created a ca.pem CERTIFICATE File and a CERTIFICATE server_cert.pem and a server_key.pem PRIVATE KEY (signed from ca.pem) as a Server. The key for CA and the Server are different:
For my MQTT-Client, under ADVANCED, CERTIFICATES, SERVER CERTIFICAT (CA) I selected the ca.pem File. If I select "Encryption", it works. But if select "validate certificate", error: Hostname/IP does not match certificate's altnames: IP: 127.0.0.1 is not in the certs list
Unfortunately I don't know what I'm doing wrong, thanks in advance :(
MQTT Explorer is built using Node.js and the MQTT library MQTT.js. As per this issue:
Node.js requires the IP address to be in the subjectAltNames for the cert and not in the CN. Maybe MQTT.fx isn't requiring that, but it should.
and:
If your server's certificate says CN=localhost in the Subject field, connect using localhost and not 127.0.0.1 and it should work. If it says CN=127.0.0.1, you have to make a new one because Node.js won't validate the IP address unless it's in the SAN extension. There is a way to work around it in code (I think it's an option called checkServerIdentity), but I would prefer to fix my certificate if I had this problem.
A rationale for the approach taken in Node is set out in this answer which includes the following quote from RFC2818: HTTP Over TLS
:
In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI.
As you are using MQTT over TLS (as opposed to HTTP Over TLS) you could argue that the above does not apply but, given that the main use of the TLS library is for HTTP traffic, it makes sense that it confirms to the RFC by default.
You have a few options including:
Use a hostname (e.g. localhost) rather then an IP when creating the certificate/connecting.
Add the IP as a subjectAltName
Modify the library to use a noop checkServerIdentity (see this answer).
Use another application for testing (not really recommended as some applications will work and others will not). The issue quoted above mentions that MQTT.fx works.

Axios with React gives 200 (304 in network tab), but gives junk HTML response

I seem to be missing a key piece here. Any ideas?
componentDidMount(){this.retrieveConfig();}
retrieveConfig = () => {const { locnNbr } = this.props.data;
axios.get(`/some/uri/stuff`).then(res => 
{console.log('retrieveConfig res', res);
this.setState({config: res. data});
});
};
componentDidMount = () => {
this.retrieveConfig();
};
retrieveConfig = () => {
Axios.get("https://jsonplaceholder.typicode.com/todos/1")
.then(res => console.log(res.data))
.catch(err => console.log(err));
};
I hope this fixes your problem.
Html response you got only for mobile and it will work from postman because the url you are trying to hit from server mobile will not able to hit. So you add the cer to your mobile.
public certificate of server where as postman allows it but mobile does not allow to hit all server urls
Consider double checking your URLs.
I'm assuming you're trying to reach a REST API endpoint but you're getting a web page as your response, which for me would suggest you're hitting the wrong port on the right domain. I believe Axios defaults to using port 8080 (web default), and it's unlikely your API is running on that port. So make sure you're specifying your URL like:
Axios.get("http://sub.domain.com:123/endpoint").then...
If you could share which URL you're using in browser and in Postman that might give more information on what's going on differently there.
The 200/304 thing makes sense from that perspective as well. It's a 200 since the request went fine but Chrome is caching the request for that web page and it's reporting that it hasn't changed (that's what 304 means).
Sometimes I come across this issue in Firefox Developer Edition and I have not figured out why this happens (I believe it has to do with the response headers).
I manage to fix it every time by clearing the browser's cache.

Service workers - testing on mobile with ngrok

I'm incorporating service workers into my meteor app; everything works fine on desktop browsers so I'm trying to test it out on mobiles.
So the app is running on localhost and I'm running ngrok so I can access on my phone. When the code tries to install the service worker, I get the following error:
SecurityError: Failed to register a ServiceWorker: the origin of the provided scriptURL (localhost:3000) does not match the current origin (https://abc123.ngrok.io)
Is there any way around this so I can play with service workers on my phone during development?
(Here is my setup in case it makes a difference - it's pretty standard)
try {
navigator.serviceWorker.register(Meteor.absoluteUrl('sw.js')).then((registration) => {
return registration.pushManager.getSubscription()
.then((subscription) => {
if(subscription) {
return subscription;
}
const reg = registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(publicKey)
});
return reg;
})
.then((subscription) => {
savePushRegistration.call({ pushSubscription: JSON.stringify(subscription) });
});
})
.catch((error) => {
console.info('Can\'t load SW', error); //This is where the error appears
});
} catch (e) {
// We're good here
// Just an old browser
}
});
I run HTTPS web servers on my laptop that my devices can connect to if they're on the same WiFi network. I configure custom CNAMEs with short TTL (5 minutes) for my domain and provide my laptop's IPs for them. My laptop server listens for those hostnames:
https://laptop-home.example.com
https://laptop-work.example.com
https://laptop-secret-lair.example.com
Getting HTTPs running locally on your computer is beyond the scope of this question, but you should create your own self-signed certificates using a custom CA Root certificate that you can install and trust on your phone. Then, you'll avoid SSL warnings when browsing to all of your self-signed sites.
A little more work than using a remote server, but well worth it if you want to avoid outside servers.

Only allow computers on the same network using Express-ip-filter

So I'm using localtunnel to expose my ports over the internet, but I only want to let devices on the same network as the server access the server.
I'm using express-ip-filter to filter away anything that's on a different network. I tried a few things: first I tried using 192.168.1.0/24 as the only ips that could access the website, but that didn't work, as it didn't let anything in. I then tried using the ip I got from WhatsMyIp, but that wouldn't let any device in. I then found out that express-ip-filter spits out a message saying that a certain ip was not allowed and, on every device, independently on the network it was connected to, the address was 127.0.0.1. I tried confirming by only allowing 127.0.0.1, and then every device could access the server. Why would ip-filter only get 127.0.0.1 as ip? Here's my code as a reference:
// Init dependencies
var express = require('express'),
ipfilter = require('express-ipfilter').IpFilter
app = express()
// Blacklist the following IPs
var ips = ['192.168.1.0/24']
// Create the server
app.use(ipfilter(ips, { mode: "allow" }))
app.get('/', function (req, res) {
res.send('Hi')
})
app.listen(8080, () => console.log('Up'))
From my limited understanding of localtunnel it seems like it proxies users requests to you via the localtunnel software which causes all users to have the same IP. In laymans terms:
User connects to your site through localtunnel
localtunnel copies the users request and sends it to your computer
Your application receives the request but it looks like all traffic is coming from localtunnel because it's incredibly difficult if not impossible for localtunnel to imitate someone else's IP.
Why use localtunnel at all if you only want devices on the same network to connect, you don't need to do any port forwarding or DNS setup if you just want to access another machine on the same local network.
If you really do need to tunnel connections then there is a solution, not with localtunnel(Which as far as i can tell does not use forwading headers, although if someone knows if they do ill change my answer) but using https://ngrok.com instead which does exactly the same thing but also sends a little extra bit of data in every request which tells the application what the clients actual IP is.
Install ngrok
Run ngrok http -subdomain=(the subdomain you want) 80
Edit your application code to find the real client IP
var findProxyIP = function(req) {
var realIP = req.header('x-forwarded-for');
return realIP;
}
app.use(ipfilter(ips, {
mode: "allow",
detectIP: findProxyIP
}));
ngrok is much more complex and has a lot more features compared to localtunnel, however, it is freemium software and its free plan is quite limiting.

Categories

Resources