How to set message in express api and get that message in react native app

Viewed 85

I am trying to send data to express api from react native, and when data is stored in mongodb return the message. i am trying to recieve the message in react native app.

I have tried these

1st Method

App.js

var inputData = {
    "email": text,
    "password": number
}

fetch('http://192.168.43.246:4000/api/addUser', {
    method: 'POST',
    body: JSON.stringify(inputData),
    headers: {
        'Content-type': 'application/json; charset=UTF-8',
    },
})
    .then((response) => console.log(response.text()))

Contoller.js

addNewUser: function(req, res) {
    data = "User Registered Successfully..."
    return res.send(data)

The response from this request is

Promise {
    _U: 0,
        _V: 0,
            _W: null,
                _X: null
}
_U: 0
_V: 1
_W: "User Registered Successfully..."

2st Method

App.js

var inputData = {
    "email": text,
    "password": number
}

fetch('http://192.168.43.246:4000/api/addUser', {
    method: 'POST',
    body: JSON.stringify(inputData),
    headers: {
        'Content-type': 'application/json; charset=UTF-8',
    },
})
    .then((response) => console.log(response))

Contoller.js

addNewUser: function(req, res) {
    data = "User Registered Successfully..."
    return res.send(data)

The response from this request is

Response {type: "default", status: 200, ok: true, statusText: "", headers: Headers, …}
bodyUsed: false
headers: Headers {map: {…}}
ok: true
status: 200
statusText: ""
type: "default"
url: "http://192.168.43.246:4000/api/addUser"
_bodyBlob: Blob {_data: {…}}
_bodyInit: Blob {_data: {…}}
__proto__: Object

How to recieve that message in react native that is sent from express api

1 Answers

You're really close to it. In the frontend part, response.text() return a promise, we need to add another then block to get the data

var inputData = {
    "email": text,
    "password": number
}

fetch('http://192.168.43.246:4000/api/addUser', {
    method: 'POST',
    body: JSON.stringify(inputData),
    headers: {
        'Content-type': 'application/json; charset=UTF-8',
    },
})
   .then(response => response.text())
   .then(data => console.log(data));

You can find more information about fetch method here

Related