Ionic 2 Http.post hangs nodeJS express server - node.js

I have a CouchDB database, and a nodeJS with express to make an API using couchdb-promises library.
In ionic 2 provider I do:
login(credentials) {
let params = {
username: credentials.email.toLowerCase(),
password: SHA3(credentials.password).toString()
};
return new Promise((resolve, reject) => {
this.http.post(API + '/auth/login', params)
.map(res => res.json())
.subscribe(data => {
localStorage.setItem('user', JSON.stringify(data.user));
resolve(true);
});
},
error => {
reject(Error(error._body));
});
});
}
It works fine the first time, but if I logout and try again, request hangs server and does not work. I need to restart server app in order to login again.
If I request via curl, I can post as many times as I want, but if I first login in Ionic 2 app, and then I send a curl request, I have not response either.
I first thougth it is problem in server side (and I tried other versions of nodejs), but only happens if I do the Ionic Http.post. Other request also hangs server, not only login. Seems only can be done one request at all.
What could be happening? Should I finalize the requests in any way?
Cordova CLI: 6.3.1
Ionic CLI Version: 2.2.1
Ionic App Lib Version: 2.2.0
OS: Linux 4.4
Node Version: v7.8.0
express: 4.15.2
couchdb-promises: 3.0.0

The problem is not Ionic 2 itself, using in server nano instead of couchdb-promises works fine.
Still having no idea why couchdb-promises hangs with Ionic and does not with normal request.

Related

Error while running typescript node using geo-tz in build file

I am using geo-tz in our Typescript Nodejs application for getting the geolocation details. When i am running the node server locally, it's working fine but when taken a node server build , i am getting an error like the below while calling geo-tz function like this:
import * as geoTz from 'geo-tz';
const testGeotz= ()=>{
try{
const coords = [-122.350070,47.650499]
let name = geoTz(coords[1], coords[0])[0];
}catch (e) {
console.log(e);
}
}
Why is it happening like this ?
My node version - 12.16.3
geo-tz version - 6.0.0
I even tried downgrading the geo-tz version and tried to upgrade to latest v6.0.1 .Still same response.
Please tell me whether I have missed out any dependency .

How do I connect React native app with node js?

I have already created backend using node js for sigin & signup page. Now I want to connect to node js . But i have no idea how to do that. I want to connect both react native with my node js. Can you help me ?
simply as how we do for web apps.
here is an example of error reporting
export default async function (body) {
console.log(JSON.stringify(body))
const res = await fetch(`${host}/api/report`, {
method: 'POST',
body: JSON.stringify(body),
headers: {
'Content-Type': 'application/json',
},
})
const { message } = await res.json()
if (message) return Toast({ message: message });
else return Toast({ message: 'network error' });
}
I have used fetch to send a POST request to my nodejs server
use API tool like postman or other and make your your nodejs APIs works fine and then connect to your React Native app as above.
You can use ngrok to connect Node with react-native. Run this command:
npm i ngrok -g # installing it globally
Then open another terminal. Run:
ngrok http 3000 # the port you are running on node
Then it will show an alternative link that you can use to test with your Node.
Note: if ngrok http 3000 doesn't work, try ngrok http -region us 3000.
The available ones are us, eu, ap, and au. In my case eu worked for me.
Then copy the link generated e.g. http://8074-129-205-124-100.eu.ngrok.io and test your backend if it displays APIs.
If the link works then you can use it with fetch. Uploading json data to send to MongoDB as the case maybe.

Suddenly started encountering Internal Server Error 500 on Mac for React App with Express server

In my react app I have an API that I am calling from my redux-saga. I am using express for my server. The code has been hosted and is working just fine. But today, I deleted the build directory and reran npm run build and then npm start and started getting this error on my local Mac.
Error on Chrome:
The error in index.js expanded if it helps:
Error on Safari:
I am pretty sure my code is proper as it has been running just fine for months now and I have made no major changes right now expect adding some console.log statements.
My API in Express Server:
app.get("/api/getProblems", (req, res) => {
var sheetKey = SECRET_KEY;
tabletop.init({
key: sheetKey,
callback: (sheet) => {
res.json(sheet);
console.log("Sent list of problems");
},
simpleSheet: true,
});
});
Calling from Saga:
function* fetchProblems() {
const data = yield call(() =>
fetch("/api/getProblems")
.then(response => response.json())
.then(sheet => sheet)
);
//Rest of the logic
}
For a brief moment I was seeing the following error:
Could not proxy request /api/getProblems from localhost:3000 to http://localhost:8000 (ECONNREFUSED)
But then it was replaced by the above error.
It was my mistake in starting the server. I ran npm start in the wrong folder. From the root I had to run the following commands:
cd client; npm run build; cd ..; npm start;

Axios (in React-native) not calling server in localhost

I'm building a really easy api and react-native application. The server works well (tested with PostMan) but the application doesn't call the server. It blocks when axios has to send the post request (see below).
I'm desperate :-( Loosing too mush time in it. Please, if you can help me...
Here is my code LogIn page. It dispatch the action creator (working with redux) giving email and password:
...
const LogIn = React.createClass({
submitLogin() {
// log in the server
if (this.props.email !== '' && this.props.psw !== '') {
if (this.props.valid === true) {
this.props.dispatch(logIn(this.props.email, this.props.psw));
} else {
this.props.dispatch(errorTyping());
}
}
},
...
email and password are weel retrieved and sent to the action creator:
import axios from 'axios';
import { SIGNIN_URL, SIGNUP_URL } from '../api';
// import { addAlert } from './alerts';
exports.logIn = (email, password) => {
return function (dispatch) {
console.log(email);
console.log(password);
console.log(SIGNIN_URL);
return axios.post(SIGNIN_URL, { email, password })
.then(
(response) => {
console.log(response);
const { token, userId } = response.data;
dispatch(authUser(userId));
}
)
.catch(
(error) => {
console.log('Could not log in');
}
);
};
};
const authUser = (userId) => {
return {
type: 'AUTH_USER',
userId
};
};
...
The three console.log() before axios show the data in the correct way. SIGNIN_URL is exactly the same I use in postman. ...but axios doesn't call.
Just to give all the cards, this is my store:
import thunk from 'redux-thunk';
import { createStore, compose, applyMiddleware } from 'redux';
import { AsyncStorage } from 'react-native';
import { persistStore, autoRehydrate } from 'redux-persist';
import reducer from '../reducer';
const defaultState = {};
exports.configureStore = (initialState = defaultState) => {
const store = createStore(reducer, initialState, compose(
applyMiddleware(thunk),
autoRehydrate()
));
persistStore(store, { storage: AsyncStorage });
return store;
};
There's no error message in the debugger (but the one given by the axios call ('Could not log in')
I'm on windows 10, with:
"axios": "^0.15.3",
"react": "15.4.2",
"react-native": "0.38.0",
"redux": "^3.6.0"
The call fails even when I prepare a simple GET call and the server is supposed to give back a simple message (tested with postman and browser):
exports.test = () => {
return function () {
return axios.get('https://localhost:3000/v1/test')
.then(
(response) => {
console.log(response);
}
)
.catch(
(error) => {
console.log('error');
}
);
};
};
Last, I tryed also to modify the call adding a header as the following, because the api is coded to accept json:
const head = {
headers: { 'Content-Type': 'application/json' }
};
exports.test = () => {
return function () {
return axios.get('https://api.github.com/users/massimopibiri', head)
.then(
(response) => {
console.log(response);
}
)
.catch(
(error) => {
console.log('error');
}
);
};
};
but even this didn't work. hope somebody can help me. Other similar issues didn't.
The solution came from a different source, but I post it here to help others looking for the same issue. Basically I used Android AVD (emulator) to build the application. But the emulator is in fact another machine, and that's why it couldn't call the localhost.
To solve the probleme, I had to send the request in the following way:
https://10.0.2.2:3000/v1/test
instead of:
https://localhost:3000/v1/test
if u are using mac this solution worked for me.
I am using React Native with Android Simulator ADV. Nexus Api 27
axios.get('http://192.168.1.21:8686/api/v1/test')
.then(response => console.log(response))
.catch(err => console.log(err));
where the ip 192.168.1.21 is from system preferences > Network > Advanced > TCP/IP > IPv4 Address
I also tested axios.get('http://10.0.2.2:8686/bec/api/v1/test') where 10.0.2.2 is localhost from virtual machine to the computer but not worked.
Your Emulator is a device on it's own that is not running on the same IP(localhost or 127.0.0.1) as your web browser, postman or your server.
In order to make request to your server from your emulator you need to access your server via your computer IP Address:
On windows get your IP Address by running ipconfig on the command prompt
On Unix terminal (Linux, Mac OS) run ifconfig to get your IP Address
Instead of http://localhost:port you should use http://your_ip_address:port
I didn't test it on Linux, Mac OS but its working perfectly on windows!
change from localhost to your ip
add http://
http://192.168.43.49:3000/user/
Another solution is to create a hosted network on the localhost computer with these commands from admin cmd:
netsh wlan set hostednetwork mode=allow ssid=wifi_name key=wifi_password
netsh wlan start hostednetwork
Connect your device to the computer's hotspot then get the computer's ip by running:
ipconfig
Now get the IPV4 address and put it on the app's axios/fetch url,
axios.get('https://192.168.137.1:3000/api')
.then(
(response) => {
console.log(response);
}
)
.catch(
(error) => {
console.log('error');
}
);
and it should now work!
I found another solution to the axios.get not working in react native problem:
Problem:- Object not visible and error: unhandled promise. Network error
Solution:-- Use below command:
=>>> npm install -g --save axios
instead of npm install --save axios i.e. Use -g.
And also check whether your emulator is having internet connection.
If your emulator is not having internet connection and is showing error such as: DNS probe finished bad config​., then
STOP ANDROID STUDIO Emulator and run these two commands in terminal
1.>> C:\Users\Admin\AppData\Local\Android\sdk\emulator\emulator.exe -list-avds​
My Output:
Pixel_XL_API_27
​
After this step, you will get the name of avds.
example:- Pixel_XL_API_27​
Now run below command:-
2.>> C:\Users\Admin\AppData\Local\Android\sdk\emulator\emulator.exe -avd Pixel_XL_API_27 -dns-server 8.8.8.8​
I have also faced similar issue and I am using Expo CLI for building and running my React Native application. My backend Express API are also running on same machine. So in my case Axios call is executing from inside Android Virtual Device emulator due to which localhost call is failing. So instead of using localhost I have used IP address and it worked!
If you are using expo client, please check hotspot IP address like 192.168.x.x (in my case ip is of this type) something on Metro Server Page.
If you are not using expo, then check your IP address using following commands :
ipconfig /all (On Windows)
ifconfig -a (OnLinux/Mac)
And then in axios api call, use http://192.168.x.x and if you are using https then use https but mostly for development purpose, you can go with http. But make sure in production environment, it is always good to use https with your domain or subdomain for providing additional security.
Alternate way to solve this issue if connecting a different way doesn't work. As others have said, because the phone is a different machine you can't use localhost. But you can use a tunnel. This will give you a url (open to the whole internet) that replicates your localhost.
Install the package localtunnel globally (yarn global add localtunnel)
Make sure your server is running, and note the port (for example, http://localhost:8081)
In another terminal/command prompt, run the localtunnel command (for me, this was npx localtunnel --port 8081). This will create your server that you can hit from the open web.
You can now replace the url in your react-native app with the url from the console
I hope this helps someone.
For me 'https://10.0.2.2:3000' was not working. I tried to map the localhost:3000 to a URL by ngrok and used that URL
./ngrok http 3000 (running this command on terminal will start session with global URL mapped to localhost port 3000)
Remeber,For this you should have ngrok installed on your system
Try Turning off your firewall it worked for me
Adding Cors to my Express App worked for me.
I did an npm install cors in the terminal in my Express server folder.
And then I just randomly added the following 2 lines of code to my Express server.js file:
const cors = require('cors');
app.use(cors())
Oh and then I specified the exact port in all my axios requests like below:
axios.post('http://localhost:5000/api/users/login/')
My problem: some ports were working for an expo app while the desired one 4000 wasn't. I wondered why. After much time researching, I found the workaround on Linux Mint: the Firewall.
Make sure you are connected over the same network and configured your server properly.
Go to Menu and search for Firewall in the machine hosting your server.
Turn status off or add a firewall rule through the plus icon at the left bottom corner.
Select Simple configuration and put your port there.
Done!

TypeError: require(...).connect is not a function

node version: v4.4.4
npm version: 3.9.2
ionic version (app): 2.0.0-beta.7
amqplib version: 0.4.1
I am currently trying to develop an app using Ionic 2 framework and I have decided to introduce messaging in my app by using RabbitMQ within this library. Feel free to inspect the code here for any further reference.
First of all, I installed the library manually using npm install https://github.com/squaremo/amqp.node.git because the release version from npm is outdated.
After that, I added the Typescript definitions for the library via typings install dt~amqplib --global --save.
I created a new page for my app called Page2 where the library is imported...
import * as amqp from 'amqplib/callback_api';
[...]
... and used to connect to the server...
[...]
setConnection() {
amqp.connect(this.connectionUrl, (err: any, connection: amqp.Connection) => {
this.connection = connection;
this.connection.createChannel((err: any, channel: amqp.Channel) => {
this.channel = channel;
this.channel.assertExchange(this.exchange, 'topic', { durable: false });
});
});
}
[...]
The problem comes when I try to run it (I have done it using both an emulator and a native device running Android). If I try to hit the Set connection button, I get the following error:
The error is linked to the line sock = require('net').connect(sockopts, onConnect); of connect.js file. Is there any trouble with NodeJS Net module in the library or is it a misconfiguration I made somewhere in my app?, thanks in advance.
There is no nodeJS server in an ionic app that your library can use.

Resources