1

I am trying to send data from the front end( react native) to back end(express) using Axios POST request I test the back end it can take data and save it in the database and the front end can handle change for the input text but when I try to send data from front end to the database by post, I cant fetch it this is the back end

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;

this is the front end

// 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 Answers 2

1

By doing this :

this.setState({ name: text });

You are erasing your previous state, replacing it with just the name. try doing something like :

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

wherever you modify your state.

I suppose you couldn't fetch it after a POST because data in your backend were incorrect.

Sign up to request clarification or add additional context in comments.

Comments

0

try this ==>

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.