开发者问题收集

如何使用 React Native 处理 axios post 请求

2020-07-19
4719

我正在尝试使用 Axios POST 请求将数据从前端(react native)发送到后端(express) 我测试了后端,它可以获取数据并将其保存在数据库中,并且前端可以处理输入文本的更改,但是当我尝试通过 post 将数据从前端发送到数据库时,我无法获取它 这是后端

var express = require("express");
var mongoose = require("mongoose");
var items = require("./models/user");
var jwt = require("jsonwebtoken");
var cors = require('cors')
var bcrypt = require("bcrypt");
var saltRounds = 10;
var Nany = items.Nany;
var User = items.User;


const dashboardRoutes = require("./dashboard");

// app.use(express.json())
// app.use("/api/user", authRoutes)
// this route is protected with token
// app.use("/api/dashboard", verifyToken, dashboardRoutes);
var app = express();
app.use(cors())
var port = process.env.PORT || 5000;

var items = require("./models/user");
require("dotenv").config(); // to read .env file

// test get req
app.get("/", function (req, res) {
  console.log("test");
  res.send("server is a go!");
});

app.post("/signup", function (req, res) {
  console.log(req);
  var newUser = new User({
    email: req.query.email,
    password: req.query.password,
    name: req.query.name,
    phoneNumber: req.query.phoneNumber,
  });
  console.log(newUser, "Sura");

  User.findOne({ email: newUser.email })
    .then((profile) => {
      if (!profile) {
        bcrypt.hash(newUser.password, saltRounds, function (err, hash) {
          if (err) {
            console.log("Error is", err.message);
          } else {
            newUser.password = hash;
            newUser
              .save()
              .then(() => {
                res.send("User authenticated");
              })
              .catch((err) => {
                console.log("Error is ", err.message);
              });
          }
        });
      } else {
        res.send("User already exists...");
      }
    })
    .catch((err) => {
      console.log("Error is", err.message);
    });
});




app.listen(port, () => {
  console.log(`Server is running on ${port} Visit https://localhost:${port}`);
});
// middleware to validate token
const verifyToken = (req, res, next) => {
  const token = req.header("auth-token");
  if (!token) return res.status(401).json({ error: "Access denied" });
  try {
    const verified = jwt.verify(token, process.env.TOKEN_SECRET);
    req.user = verified;
    next(); // to continue the flow
  } catch (err) {
    res.status(400).json({ error: "Token is not valid" });
  }
};
module.exports = verifyToken;

这是前端

// import EnterName from './App/Components/EnterName

// import EnterName from './App/Components/EnterName
import axios from "axios";
import React from "react";

import {
  Text,
  AppRegistry,
  View,
  StyleSheet,
  TouchableOpacity,
  TextInput,
  ScrollView,
} from "react-native";
import { requireNativeViewManager } from "expo-core";

export default class SignUpInputs extends React.Component {
  state = {
    email: "",
    password: "",
    name: "",
    phoneNumber: "",
  };
  handleEmail = (text) => {
    this.setState({ email: text });
  };
  handlePassword = (text) => {
    this.setState({ password: text });
  };
  handlename = (text) => {
    this.setState({ name: text });
  };
  handlephoneNumber = (text) => {
    this.setState({ phoneNumber: text });
  };

  // SingUp = (email, pass) => {
  //   alert("email: " + email + " password: " + pass);
  SingUp = (email , pass ,name,phoneNumber ) => {
    // alert("email: " + email + " password: " + pass);}
    console.log(email , pass ,name,phoneNumber)
   axios
      .post("http://localhost:5000/signup", {
        email: email,
        password: pass,
        name:name,
      phoneNumber:phoneNumber

      })
      .then((response) => {
        console.log("fnh", response);
      })
      .catch((err) => {
        throw err;
      });
  };

  // };

  render() {
    return (
      <ScrollView style={{ padding: 20 }}>
        <View>
          <View>
            <TextInput
              style={style.inputs}
              onChangeText={(text) => onChangeText(text)}
              placeholder="Enter email"
              type="email"
              onChangeText={this.handleEmail}
            />
          </View>

          <View>
            <TextInput
              secureTextEntry={true}
              style={style.inputs}
              placeholder="Enter Password"
              onChangeText={this.handlePassword}
            />
          </View>
          <View>
            <TextInput
              style={style.inputs}
              placeholder="Enter Name"
              onChangeText={this.handlename}
            />
          </View>
          <View>
            <TextInput
              style={style.inputs}
              placeholder="Enter Phone Number"
              type="tel"
              onChangeText={this.handlephoneNumber}
            />
          </View>

          <TouchableOpacity
            style={style.submitButton}
            onPress={() =>
              this.SingUp(
                this.state.email,
                this.state.password,
                this.state.name,
                this.state.phoneNumber
              )
              
            }
          >
            <Text style={style.textButton}>Sign Up </Text>
          </TouchableOpacity>
        </View>
      </ScrollView>
    );
  }
}
const style = StyleSheet.create({
  inputs: {
    marginTop: 50,
    color: "#6FE6E0",
    fontSize: 20,
    marginLeft: 10,
    marginRight: 10,
    borderBottomColor: "#6FE6E0",
    borderBottomWidth: 2,
  },
  textButton: {
    width: 140,
    padding: 10,
    fontSize: 20,
    marginTop: 10 + "%",
    marginLeft: "auto",
    marginRight: "auto",
    fontWeight: "bold",
    borderRadius: 30,
    color: "white",
    textAlign: "center",
    backgroundColor: "#E88877",
  },
});
2个回答

通过这样做:

this.setState({ name: text });

您将删除以前的状态,而仅用名称替换它。尝试执行以下操作:

this.setState({ ...this.state, name: text });

无论您在何处修改状态。

我想您无法在 POST 之后获取它,因为后端的数据不正确。

Quentin Grisel
2020-07-19

尝试一下 ==>

axios
      .post("http://192.168.127.43:5000/sendSMS", valuesToSend)
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
Sura Aloqaily
2020-07-26