来自 axios 的 POST 请求出现网络错误

发布于 2025-01-10 16:20:40 字数 4368 浏览 0 评论 0原文

我正在使用 axios 发出 GET 和 POST 请求来验证用户身份。当我使用 Postman 时,一切正常,如下面的屏幕截图所示

在此处输入图像描述

由于我能够通过输入用户名、电子邮件和密码成功发出 POST 请求,因此我想在我的应用程序中使用 axios React Native 应用程序如此该 HTTP 请求负责注册新用户。但是,当我尝试注册新用户时遇到“网络错误”。

这是我的 React 代码,我想在其中与 API 通信以注册用户

import React, { useState } from "react";
import styles from "./styles";
import axios from "axios";
import { NativeBaseProvider, VStack, Input, Button, Text } from "native-base";
import { MaterialCommunityIcons } from "@expo/vector-icons";
import { COLORS } from "../../util/colors";

//problem may be here...?
const registerUser = async (username, email, password) => {
  axios
      .post(
        `http://localhost:5050/register`, {
          username: username,
          email: email,
          password: password,
        },
        {
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
          }
        }
        )
      .then((response) => {
        console.log(response);
      })
      .catch((error) =>
      console.log(error));
    };

function RegisterScreen(props) {
  const [username, setUsername] = useState("");
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  return (
    <NativeBaseProvider>
      <VStack w="100%" space={5} alignItems="center" style={styles.container}>
        <MaterialCommunityIcons name="jellyfish" size={60} color="black" />
        <Input
          value={username}
          onChangeText={setUsername}
          placeholder="Username"
          borderRadius="10"
          py="2"
          px="3"
          fontSize="14"
          w="80%"
          mb="-2"
        />
        <Input
          value={name}
          onChangeText={setName}
          placeholder="Name"
          borderRadius="10"
          py="2"
          px="3"
          fontSize="14"
          w="80%"
          mb="-2"
        />
        <Input
          value={email}
          onChangeText={setEmail}
          placeholder="Email"
          borderRadius="10"
          py="2"
          px="3"
          fontSize="14"
          w="80%"
          mb="-2"
        />
        <Input
          type={"password"}
          value={password}
          onChangeText={setPassword}
          placeholder="Password"
          borderRadius="10"
          py="2"
          px="3"
          fontSize="14"
          w="80%"
          mb="-2"
        />
        <Button
          onPress={() =>  registerUser(username, email, password)
            //here i am registering a use, wan to call function that calls API
            //console.log("Registering: ", username, name, email, password)
          }
          w="40%"
          py="4"
          style={styles.button}
        >
          <Text fontSize="lg" bold color={"white"}>
            Register
          </Text>
        </Button>
      </VStack>
    </NativeBaseProvider>
  );
}

export default RegisterScreen;

作为参考,以下是我的路由器是如何为注册 POST 请求定义的

router.post("/register", async (req, res) => {
  try {
    const { username, email, password } = req.body;
    const data = await users.create({
      username,
      email,
      password,
      role: "CLIENT",
    });
    res.status(201).json({ data });
  } catch (err) {
    res.status(err.status || 500).json({ message: err.message });
  }
});

当我运行以下代码并且用户在 React 本机应用程序的文本框中输入用户名、电子邮件和密码时,出现以下错误:

Network Error
at node_modules/axios/lib/core/createError.js:16:14 in createError
at node_modules/axios/lib/adapters/xhr.js:117:24 in handleError
at node_modules/react-native/Libraries/Network/XMLHttpRequest.js:609:10 in setReadyState
at node_modules/react-native/Libraries/Network/XMLHttpRequest.js:396:6 in __didCompleteResponse
at node_modules/react-native/Libraries/vendor/emitter/_EventEmitter.js:135:10 in EventEmitter#emit

任何见解都非常感激!

I am using axios to make GET and POST requests to authenticate a user. Everything works fine when I am using Postman, as seen by the screenshot below

enter image description here

Since I am able to make a POST request successfully by inputting a username, email, and password, I want to use axios in my React Native app so that this HTTP request takes care of registering a new user. However, I run into a 'Network error' when I try to register a new user.

Here is my React code where I want to communicate with my API to register a user

import React, { useState } from "react";
import styles from "./styles";
import axios from "axios";
import { NativeBaseProvider, VStack, Input, Button, Text } from "native-base";
import { MaterialCommunityIcons } from "@expo/vector-icons";
import { COLORS } from "../../util/colors";

//problem may be here...?
const registerUser = async (username, email, password) => {
  axios
      .post(
        `http://localhost:5050/register`, {
          username: username,
          email: email,
          password: password,
        },
        {
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
          }
        }
        )
      .then((response) => {
        console.log(response);
      })
      .catch((error) =>
      console.log(error));
    };

function RegisterScreen(props) {
  const [username, setUsername] = useState("");
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  return (
    <NativeBaseProvider>
      <VStack w="100%" space={5} alignItems="center" style={styles.container}>
        <MaterialCommunityIcons name="jellyfish" size={60} color="black" />
        <Input
          value={username}
          onChangeText={setUsername}
          placeholder="Username"
          borderRadius="10"
          py="2"
          px="3"
          fontSize="14"
          w="80%"
          mb="-2"
        />
        <Input
          value={name}
          onChangeText={setName}
          placeholder="Name"
          borderRadius="10"
          py="2"
          px="3"
          fontSize="14"
          w="80%"
          mb="-2"
        />
        <Input
          value={email}
          onChangeText={setEmail}
          placeholder="Email"
          borderRadius="10"
          py="2"
          px="3"
          fontSize="14"
          w="80%"
          mb="-2"
        />
        <Input
          type={"password"}
          value={password}
          onChangeText={setPassword}
          placeholder="Password"
          borderRadius="10"
          py="2"
          px="3"
          fontSize="14"
          w="80%"
          mb="-2"
        />
        <Button
          onPress={() =>  registerUser(username, email, password)
            //here i am registering a use, wan to call function that calls API
            //console.log("Registering: ", username, name, email, password)
          }
          w="40%"
          py="4"
          style={styles.button}
        >
          <Text fontSize="lg" bold color={"white"}>
            Register
          </Text>
        </Button>
      </VStack>
    </NativeBaseProvider>
  );
}

export default RegisterScreen;

For reference, here is how my router is defined for the register POST request

router.post("/register", async (req, res) => {
  try {
    const { username, email, password } = req.body;
    const data = await users.create({
      username,
      email,
      password,
      role: "CLIENT",
    });
    res.status(201).json({ data });
  } catch (err) {
    res.status(err.status || 500).json({ message: err.message });
  }
});

When I run my following code and a user inputs a username, email, and password into the text-boxes of my React native app, I get the following error:

Network Error
at node_modules/axios/lib/core/createError.js:16:14 in createError
at node_modules/axios/lib/adapters/xhr.js:117:24 in handleError
at node_modules/react-native/Libraries/Network/XMLHttpRequest.js:609:10 in setReadyState
at node_modules/react-native/Libraries/Network/XMLHttpRequest.js:396:6 in __didCompleteResponse
at node_modules/react-native/Libraries/vendor/emitter/_EventEmitter.js:135:10 in EventEmitter#emit

Any insight is much appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文