Create A REST API With JSON Server /Mock Server
Initial setup
start ==>
npx nodemon app
React Native
Code
import React, { Component } from 'react'
import { View, Text, Button } from 'react-native'
class App extends Component {
constructor(props) {
super(props)
this.state = {
text: 'Click to connect the server'
}
}
connect = () => {
const URL = 'http://192.168.43.109:5000/welcome'
fetch(URL)
.then(response => {
if (response.status == 200) {
return response.text()
} else {
throw new Error('Something went wrong')
}
}).then(responseText => {
this.setState({ text: responseText })
}).catch(error => {
console.error(error.message)
})
}
render() {
return (
<View>
<Text style={{ fontSize: 25 }}> {this.state.text}</Text>
<Button title='CONNECT' onPress={this.connect}></Button>
</View>
)
}
}
export default App
Tips
C:\Users\sapan>ipconfig
IPv4 Address.
React Native
Code
import React, { Component } from 'react'
import { View, Text, Button, Alert, TextInput } from 'react-native'
class App extends Component {
constructor(props) {
super(props)
this.state = {
text: 'Click to connect the server',
name:''
}
}
setText =(text)=>{
this.setState({name:text})
}
connect = async () => {
const URL = 'http://192.168.43.109:5000/welcome'
try {
const response = await fetch(URL + "/" + this.state.name)
if (response.status != 200) {
throw new Error('Something went wrong')
}
const responseText = await response.text()
this.setState({ text: responseText })
} catch (error) {
Alert.alert(error.message)
}
}
render() {
return (
<View><TextInput placeholder='Enter name' onChangeText={this.setText}/>
<Text style={{ fontSize: 25 }}> {this.state.text}</Text>
<Button title='CONNECT' onPress={this.connect}></Button>
</View>
)
}
}
export default App
const bodyParser = require('body-parser')
const app = express()
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.get('/welcome/:name', (req, res) => {
const user = req.params.name
res.send('Welcome : ' + user)
})
app.post('/welcome', (req, res) => {
const name = req.body.name
res.send('WELCOME' + name)
})
const port = process.env.PORT || 5000
app.listen(port, () => {
console.log(`server is running on port ${ port }`)
})
Initial setup
Step -1: npm install -g json-server
Step -2: npm init
Step -2: npm init
Step -3: npm install -D json-server
Step -4: db.json
or
Step -5: yarn global add json-server
Step -6: yarn add json-server --dev
or
Step -5: yarn global add json-server
Step -6: yarn add json-server --dev
{
"users": [
{
"id": 1,
"firstName": "Sapan",
"lastName": "Das",
"active": true,
"posts": 10,
"messages": 50
},
{
"id": 2,
"firstName": "Johan",
"lastName": "Doe",
"active": true,
"posts": 8,
"messages": 5
}
]
}
step-4: run the below command
json-server --watch db.json
json-server --watch -p 5000 db.json
json-server --watch -p 5000 public/db.json
json-server public/db.json --port 8000
json-server --watch -p 5000 db.json
json-server --watch -p 5000 public/db.json
json-server public/db.json --port 8000
..........................................................................................................................................................................................................................
Keep learning :)
...........................................................................................................................................................................................................................
Example #2 [ React-native, connecting to Node.js web server ]
npm init -y
yarn add express
yarn add nodemon --dev
const express = require('express')
const app =express()
app.get('/welcome',(req,res)=>{
res.send('Welcome to my web server')
})
const port = process.env.PORT || 5000
app.listen(port,()=>{
console.log(`server is running on port ${port}`)
})
Example #2 [ React-native, connecting to Node.js web server ]
npm init -y
yarn add express
yarn add nodemon --dev
const express = require('express')
const app =express()
app.get('/welcome',(req,res)=>{
res.send('Welcome to my web server')
})
const port = process.env.PORT || 5000
app.listen(port,()=>{
console.log(`server is running on port ${port}`)
})
start ==>
npx nodemon app
React Native
Code
import React, { Component } from 'react'
import { View, Text, Button } from 'react-native'
class App extends Component {
constructor(props) {
super(props)
this.state = {
text: 'Click to connect the server'
}
}
connect = () => {
const URL = 'http://192.168.43.109:5000/welcome'
fetch(URL)
.then(response => {
if (response.status == 200) {
return response.text()
} else {
throw new Error('Something went wrong')
}
}).then(responseText => {
this.setState({ text: responseText })
}).catch(error => {
console.error(error.message)
})
}
render() {
return (
<View>
<Text style={{ fontSize: 25 }}> {this.state.text}</Text>
<Button title='CONNECT' onPress={this.connect}></Button>
</View>
)
}
}
export default App
Tips
C:\Users\sapan>ipconfig
IPv4 Address.
import React, { Component } from 'react'
import { View, Text, Button, Alert } from 'react-native'
class App extends Component {
constructor(props) {
super(props)
this.state = {
text: 'Click to connect the server'
}
}
connect = async () => {
const URL = 'http://192.168.43.109:5000/welcome'
try {
const response = await fetch(URL)
if (response.status != 200) {
throw new Error('Something went wrong')
}
const responseText = await response.text()
this.setState({ text: responseText })
} catch (error) {
Alert.alert(error.message)
}
}
render() {
return (
<View>
<Text style={{ fontSize: 25 }}> {this.state.text}</Text>
<Button title='CONNECT' onPress={this.connect}></Button>
</View>
)
}
}
export default App
Keep learning :)
......................................................................................................................................................................................................... ...................
......................................................................................................................................................................................................... ...................
Example #3 [ params ]
const express = require('express')
const app =express()
app.get('/welcome/:name',(req,res)=>{
const user = req.params.name
res.send('Welcome : ' + user)
})
const port = process.env.PORT || 5000
app.listen(port,()=>{
console.log(`server is running on port ${port}`)
})
const express = require('express')
const app =express()
app.get('/welcome/:name',(req,res)=>{
const user = req.params.name
res.send('Welcome : ' + user)
})
const port = process.env.PORT || 5000
app.listen(port,()=>{
console.log(`server is running on port ${port}`)
})
React Native
Code
import React, { Component } from 'react'
import { View, Text, Button, Alert, TextInput } from 'react-native'
class App extends Component {
constructor(props) {
super(props)
this.state = {
text: 'Click to connect the server',
name:''
}
}
setText =(text)=>{
this.setState({name:text})
}
connect = async () => {
const URL = 'http://192.168.43.109:5000/welcome'
try {
const response = await fetch(URL + "/" + this.state.name)
if (response.status != 200) {
throw new Error('Something went wrong')
}
const responseText = await response.text()
this.setState({ text: responseText })
} catch (error) {
Alert.alert(error.message)
}
}
render() {
return (
<View><TextInput placeholder='Enter name' onChangeText={this.setText}/>
<Text style={{ fontSize: 25 }}> {this.state.text}</Text>
<Button title='CONNECT' onPress={this.connect}></Button>
</View>
)
}
}
export default App
Keep learning :)
............................................................................................................................................................................................................................
Example #4 [POST]
const express = require('express')const bodyParser = require('body-parser')
const app = express()
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.get('/welcome/:name', (req, res) => {
const user = req.params.name
res.send('Welcome : ' + user)
})
app.post('/welcome', (req, res) => {
const name = req.body.name
res.send('WELCOME' + name)
})
const port = process.env.PORT || 5000
app.listen(port, () => {
console.log(`server is running on port ${ port }`)
})
React Native
Code
import React, { Component } from 'react'
import { View, Text, Button, Alert, TextInput } from 'react-native'
class App extends Component {
constructor(props) {
super(props)
this.state = {
text: 'Click to connect the server',
name:''
}
}
setText =(text)=>{
this.setState({name:text})
}
connect = async () => {
const URL = 'http://192.168.43.109:5000/welcome'
try {
const response = await fetch(URL,{
method:'POST',
headers:{
'Content-Type':'application/json'
},
body: JSON.stringify({name:this.state.name})
})
if (response.status != 200) {
throw new Error('Something went wrong')
}
const responseText = await response.text()
this.setState({ text: responseText })
} catch (error) {
Alert.alert(error.message)
}
}
render() {
return (
<View><TextInput placeholder='Enter name' onChangeText={this.setText}/>
<Text style={{ fontSize: 25 }}> {this.state.text}</Text>
<Button title='CONNECT' onPress={this.connect}></Button>
</View>
)
}
}
export default App
import { View, Text, Button, Alert, TextInput } from 'react-native'
class App extends Component {
constructor(props) {
super(props)
this.state = {
text: 'Click to connect the server',
name:''
}
}
setText =(text)=>{
this.setState({name:text})
}
connect = async () => {
const URL = 'http://192.168.43.109:5000/welcome'
try {
const response = await fetch(URL,{
method:'POST',
headers:{
'Content-Type':'application/json'
},
body: JSON.stringify({name:this.state.name})
})
if (response.status != 200) {
throw new Error('Something went wrong')
}
const responseText = await response.text()
this.setState({ text: responseText })
} catch (error) {
Alert.alert(error.message)
}
}
render() {
return (
<View><TextInput placeholder='Enter name' onChangeText={this.setText}/>
<Text style={{ fontSize: 25 }}> {this.state.text}</Text>
<Button title='CONNECT' onPress={this.connect}></Button>
</View>
)
}
}
export default App
Keep learning :)
............................................................................................................................................................................................................................
Example #5
Keep learning :)
Keep learning :)
............................................................................................................................................................................................................................
Example #6
Keep learning :)
Keep learning :)
............................................................................................................................................................................................................................
Example #7
Keep learning :)
Keep learning :)
............................................................................................................................................................................................................................
Example #8
Keep learning :)
Keep learning :)
Valuable post useful for everyone.Keep on sharing.
ReplyDeleteReact JS Online training
React JS training in hyderabad
ReplyDeleteHi everybody, I hope you are doing good. Dear admin I had scroll down your site and found it really useful for web development tools. Since I am a developer, I most often refer people to use best website in the town for web development. Your efforts are really appreciable. We also provide web development tool. Here is the link of our site jsononline