Reputation: 35
I am new to react-native. I have been following the tutorial on https://blog.theodo.fr/2017/03/how-to-create-an-authentication-system-and-a-persistent-user-session-with-react-native/ to learn how to use asyncstorage on react native. Here is the snippet of code I am stuck on:
userSignup() {
if (!this.state.username || !this.state.password) return;
// TODO: localhost doesn't work because the app is running inside an emulator. Get the IP address with ifconfig.
fetch('http://192.168.XXX.XXX:3001/users', {
method: 'POST',
headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify({
username: this.state.username,
password: this.state.password,
})
})
.then((response) => response.json())
.then((responseData) => {
this.saveItem('id_token', responseData.id_token),
Alert.alert( 'Signup Success!', 'Click the button to get a Chuck Norris quote!'),
Actions.HomePage();
})
.done();
}
I am unsure of what I should put in here 'http://192.168.XXX.XXX:3001/users'.
Where can I find my port number?
Is the IP the same one I would find if I googled "what is my ip"?
What does 'application/json' do? Is there any caveat I should know about if I were to just copy paste the fetch section word-for-word? (I also only have two states: username and password)
This is what I have written so far for the signup page:
import React, {Component} from 'react';
import {StyleSheet, Text, View} from 'react-native';
export default class signUp extends React.Component {
render() {
return (
<View style={styles.container}>
<Text>signUp</Text>
</View>
);
}
userSignUp(){
if(!this.state.username || !this.state.password) return;
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
});
Upvotes: 0
Views: 64
Reputation: 7017
I am unsure of what I should put in here 'http://192.168.XXX.XXX:3001/users'. Where can I find my port number? Is the IP the same one I would find if I googled "what is my ip"?
The note "Get the IP address with ifconfig" gives you a clue for that part. If you are on macOS (OS X) you can run ifconfig
with a result such as:
en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
ether 11:11:11:11:11:11
inet6 aaaa::aaaa:aaaa:aaaa:aaaa%en0 prefixlen 64 secured scopeid 0x5
inet x.x.x.x netmask 0xffffff00 broadcast y.y.y.y
nd6 options=201<PERFORMNUD,DAD>
media: autoselect
status: active
^ That x.x.x.x
or whatever after en0
inet
is your IP.
The value from Google is your public IP, which will be slower and may be inaccessible.
The port could be for anything, but the blog references Node.js, so it may be for the Node server. If you already have something running there, you can find it with:
lsof -nP -i4TCP | grep 3001
What does 'application/json' do?
application/json
is the content type to receive (Accept
) and send (Content-Type
); it indicates JSON, which these days is the most common format for APIs.
Upvotes: 1