如何从后端到前端使用Axios

时间:2020-10-16 21:00:49

标签: javascript reactjs express axios

我使用reactjs作为开发工具,使用mongoDB作为后端数据库。

我的后端反应代码如下:

const express = require("express");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
const { User, VerificationCode } = require("../models");
const { isLoggedIn, getLoggedInUserId, generateRefreshToken } = require("./middlewares");
const sendVerificationEMail = require("./bin/send_email").sendVerificationEmail;
require("dotenv").config();

const router = express.Router();

router.post("/register", async (req, res, next) => {
  const { email, username, password, first_name, last_name } = req.body;
  try {
    // Check if the email is duplicating
    let existingUser = await User.findOne({ where: { email } });
    if (existingUser) {
      return res.status(409).json({
        success: false,
        message: "User already exists.",
      });
    }

    existingUser = await User.findOne({ where: { username } });
    if (existingUser) {
      return res.status(409).json({
        success: false,
        message: "Same nickname user exists.",
      });
    }
    const hash = await bcrypt.hash(password, 12);
    await User.create({
      email,
      username,
      password: hash,
      first_name,
      last_name,
    });
    return res.status(200).json({
      success: true,
      message: "Signup successful.",
    });
  } catch (error) {
    return res.json({
      success: false,
      message: "Signup failed.",
    });
  }
});

// Login
// Create token and return to user (httpOnly cookies)
router.post("/login", async (req, res, next) => {
  const { email, password } = req.body;

  // Make a inquiry of the user through email
  try {
    const user = await User.findOne({ where: { email }, raw: true });
    if (!user) {
      return res.status(401).json({
        success: false,
        message: "No member exists.",
      });
    }

    // Check password
    const isMatch = await bcrypt.compare(password, user.password);
    if (isMatch) {
      // If the password matches,create JWT payload 
      const payload = {
        uid: user.id,
      };

      // JWT token create
      const token = jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: req.app.get("jwt_expiration") });

      // New refresh token and create expiration for it
      let refresh_token = generateRefreshToken(req, user.id);
      let refresh_token_maxage = new Date() + req.app.get("jwt_refresh_expiration");

      // Browswer httpOnly cookie setting
      res.cookie("access_token", token, {
        // secure: true,
        httpOnly: true,
      });
      res.cookie("refresh_token", refresh_token, {
        // secure: true,
        httpOnly: true,
      });

      // Save the account id as key and save in Redis server
      req.client.set(
        user.id,
        JSON.stringify({
          refresh_token: refresh_token,
          expires: refresh_token_maxage,
        }),
        req.client.print
      );

      return res.json({
        success: true,
        uid: user.id,
        message: "Login Successful",
      });
    } else {
      return res.status(401).json({
        success: false,
        message: "Password's don't match.",
      });
    }
  } catch (error) {
    console.error(error);
    res.status(401).json({
      success: false,
      message: "Login Error",
    });
  }
});

module.exports = router;

我的登录前端代码如下:(Login.js)

import React, { Component } from "react";
import login from "../picture/login.png";
import Form from "react-bootstrap/Form";
import axios from "axios";

export default class SignUp extends Component {

  
  render() {
  
        return (
          <div style = {{
            backgroundColor:'#f7feff'
          }}>
          <div class="container h-100">
          <div class="row h-100 justify-content-center align-items-center">
              <form class="col-6">
         
             
                <br/><br/><br/>
                <h2>Login</h2>
                <hr />

                <div class="row h-100 justify-content-center align-items-center">
                    <img src = {login}
                    width = '550'
                    height = '200'
                    alt='Login2'/>
                </div>

                 <Form.Group controlId="formBasicEmail">
                 <Form.Label>Email address</Form.Label>
                  <Form.Control type="email" placeholder="Enter email" />
                  <Form.Text className="text-muted">
                   We'll never share your email with anyone else.
                   </Form.Text>
                  </Form.Group>

                  <Form.Group controlId="formBasicPassword">
                    <Form.Label>Password</Form.Label>
                    <Form.Control type="password" placeholder="Enter password" />
                  </Form.Group>
                  <Form.Group controlId="formBasicCheckbox">
                    <Form.Check type="checkbox" label="Remember me" />
                  </Form.Group>
                  <button type="submit" className="btn btn-info btn-block">Submit</button>

                  <div className = "App-wrapper">
                
                  <p className="forgot-password text-right">
                  <a href="signup"to="/signup">
                     Sign Up   | </a>
                   <a href="password"to="/pasword">
                     Find Password</a>
      
                </p>
                </div>
              
                  
            </form>
            </div>
            </div>
            </div>
        );
    
  }
}

我的注册前端代码是:(Signup.js)

import React, { Component } from "react";
import Form from "react-bootstrap/Form";
import welcome from "../picture/welcome.png";


export default class SignUp extends Component {
    render() {
        return (
            <div style = {{
                backgroundColor:'#f7feff'
            }}>
            <div class="container h-100">
                <div class="row h-100 justify-content-center align-items-center">
                
                <form class="col-6">

                <br/><br/><br/>
                <h2>Sign Up</h2>
                <hr />

                <div class = "row h-100 justify-content-center align-items-center">
                    <img src = {welcome}
                    width = '550'
                    height = '200'
                    alt='signup'/>
                </div>
                 <Form.Group controlId="formBasicEmail">
                 <Form.Label>*Email address</Form.Label>
                  <Form.Control type="email" placeholder="Enter email" />
                  </Form.Group>

                  <Form.Group controlId="formBasicUsername">
                 <Form.Label>*Username</Form.Label>
                  <Form.Control placeholder="Enter username" />
                  </Form.Group>

                  <Form.Group controlId="formBasicPassword">
                 <Form.Label>*Password</Form.Label>
                  <Form.Control type="password" placeholder="Enter password" />
                  </Form.Group>

                  <Form.Group controlId="formBasicFirstname">
                 <Form.Label>*Firstname</Form.Label>
                  <Form.Control placeholder="Enter firstname" />
                  </Form.Group>

                <Form.Group controlId="formBasicLastname">
                 <Form.Label>*Lastname</Form.Label>
                  <Form.Control type placeholder="Enter lastname" />
                 
                  </Form.Group>

                  <Form.Group controlId="formBasicTelephone">
                 <Form.Label>Telephone</Form.Label>
                  <Form.Control type="number"placeholder="Enter telephone number"/>
                  </Form.Group>

                  <Form.Text className="text-muted">
                   Fields that are marked with asterisk(*) are compulsory.
                   </Form.Text>

                <button type="submit" className="btn btn-info btn-block">Sign Up</button>
                <p className="forgot-password text-right">
                     <a href="login"to="/login">Already registered? sign in?</a>
                </p>
            </form>
            </div>
            </div>

            </div>
            
        );
    }
}

我真的不知道如何使用axios连接后端和前端。登录服务器的URL为localhost:8002 / auth / login,用于注册的地址为:localhost:8002 / auth / signup

1 个答案:

答案 0 :(得分:1)

在React组件中,您必须创建一个使用axios调用后端的函数,然后将其作为onClick处理程序添加到提交按钮。

要向axios发送请求,您必须使用axios模块上可用的功能。在您的情况下,可能看起来像这样:

    function onSubmit() {
        axios.post('localhost:8002/auth/login', 
           {username: username, 
            password: password });
    }

请注意,axios.post返回了一个Promise,因此您必须等待它/使用.then才能从后端获得响应。使用该功能后,可以将其附加到登录按钮,如下所示:

<button type="submit" className="btn btn-info btn-block" onClick={onSubmit}>Submit</button>

编辑:用户名和密码值当然是用户通过输入字段输入的值。您可以将它们存储在组件的状态中。

相关问题