【问题标题】:React Native how to send AsyncStorage data to MongoDB database?React Native 如何将 AsyncStorage 数据发送到 MongoDB 数据库?
【发布时间】:2022-01-15 19:07:57
【问题描述】:

我无法将存储在 AsyncStorage 中的用户输入传输到我的 MongoDB 数据库 我有一个从终端开始的 MongoDB 数据库。控制台输出如下,所以应该没有任何问题:

服务器在 PORT 5000 上启动 MongoDB Connected cluster0-shard-00-02.mhqqx.mongodb.net

之后,我使用 expo go 打开我的 React Native 应用程序,然后转到我的注册屏幕,在那里应该创建一个新的用户配置文件。我将每个需要的用户输入(姓名、电子邮件等)以 JSON 格式存储在 AsyncStorage 中,如下所示:

const nameString = JSON.stringify(name)
const emailString = JSON.stringify(email)
AsyncStorage.setItem('nameInput', nameString);
AsyncStorage.setItem('emailInput', emailString);
setName('');
setEmail('');

当我在控制台打印 AsyncStorages 的值时,没有错误,数据显示正确。因此用户输入存储在 AsyncStorages 中。

但在此之后,我尝试通过使用 onPress 调用按钮触发以下函数将 AsyncStorage 数据传输到我的 MongoDB 数据库:

const submitHandler = async (e) => {

        if(password !==confirmpassword) {
            setMessage('Passwords do not match')
        } else  {
            setMessage(null)
            try {
                const config = {
                    headers: {
                        "Content-type": "application/json",
                    },
                };

                setLoading(true);

                const { data } = await axios.post(
                    "/api/users",
                    {name, email, password},
                    config
                );

                setLoading(false);
            } catch (error) {
                setError(error.response.data.message);
            }
        }

        console.log(email);
    };

当我检查数据库时,我的数据库中没有显示新信息。数据库功能正常,定义的路线应该是正确的。可能是什么问题?

我还可以像这样从 Postman 创建一个新用户:

我已经尝试为这个问题寻找一些答案一段时间了,但没有成功。非常感谢您的帮助!

【问题讨论】:

  • console.log 数据会得到什么?
  • 我得到了用户在输入字段中用引号输入的所有内容。例如,如果用户在电子邮件字段 user@gmail.com 中键入,控制台会记录“user@gmail.com”
  • 我说的是你声明的变量data。这个const { data } = await axios.post("/api/users",{name, email, password},config);
  • 当我 console.log 时它没有给我任何东西。

标签: javascript mongodb react-native axios backend


【解决方案1】:

你可以这样做

await axios.post("/api/users",
{name, email, password},config)
.then(res=> console.log(res)
.catch(err => console.log("api error", err)

然后看看你在相应的终端中得到了什么。
注意 您的 API 端点 (api/users) 无效。从您正在使用的 Postman 添加相同的 URL。

【讨论】:

    猜你喜欢
    • 2017-08-06
    • 1970-01-01
    • 1970-01-01
    • 2018-06-11
    • 2022-11-24
    • 1970-01-01
    • 2022-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多