【问题标题】:How to set message in express api and get that message in react native app如何在 express api 中设置消息并在反应本机应用程序中获取该消息
【发布时间】:2021-05-19 03:11:53
【问题描述】:

我正在尝试从 react native 发送数据以表达 api,并且当数据存储在 mongodb 中时返回消息。我正在尝试在本机应用程序中接收消息。

这些我都试过了

第一种方法

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)

这个请求的响应是

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

第二种方法

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)

这个请求的响应是

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

如何在 react native 中接收从 express api 发送的消息

【问题讨论】:

    标签: node.js react-native express


    【解决方案1】:

    你真的很接近它。在前端部分,response.text() 返回一个 promise,我们需要添加另一个 then 块来获取数据

    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));
    

    你可以找到更多关于fetch方法here的信息

    【讨论】:

      猜你喜欢
      • 2020-10-04
      • 1970-01-01
      • 2021-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-22
      • 1970-01-01
      • 2020-02-02
      相关资源
      最近更新 更多