简体   繁体   English

如何在REACT中为连接到node.js的Axios路由创建一个单独的文件夹

[英]How can i create a separate folder in REACT for my Axios routes, that are connected to my node.js

Hello I trying to create a separate folder for my axios routes. 您好,我试图为我的axios路由创建一个单独的文件夹。 I do not want them inside of my components file in React. 我不希望它们在React的组件文件中。

I have tried this under the following folder, separate from my components folder. 我在以下文件夹下尝试了此操作,与我的components文件夹分开。 src > actions > authentication src>操作>身份验证

import axios from 'axios';

export const signupUser = (user, history) => dispatch => {
  axios.post('http://localhost:3000/signup', user)
  console.log(user)
    .then(res => history.push('/login'))
    .catch(err => {
      console.log(err);

    });
};

Inside the Signup.js component I have the following, that is not currently working 在Signup.js组件中,我有以下内容,目前无法使用

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { signupUser } from '../actions/authentication';
import axios from 'axios';

let today = new Date();
let date = today.getFullYear()+ '-' +  (today.getMonth()+1)+ '-' +today.getDate();




class Signup extends Component {

  constructor() {
    super()
    this.state = {
      first_name: '',
      last_name: '',
      user_name: '',
      email: '',
      password: '',
      created_on: date,
      isSignedup: false
    }

    this.handleInputChange = this.handleInputChange.bind(this);

    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleInputChange = (e) => {
    this.setState({
      [e.target.name]: e.target.value
    })
    console.log(this.state);
  }

  handleSubmit = (e) => {
    e.preventDefault();

    const user = {

      first_name: this.state.first_name,
      last_name: this.state.last_name,
      email: this.state.email,
      user_name: this.state.user_name,
      password: this.state.password,
      created_on: this.state.created_on,
      isSignedup: !this.state.isSignedup
    }
    .then(data => {
      console.log(data);
      this.props.history.replace('/login');
    })
    .catch(err => {
      console.log(err);
    })
  }

It only works in my components > Signup.js if I have the actual axios route inside the component as follows: 如果我在组件内部具有实际的axios路由,则它仅在我的组件> Signup.js中有效,如下所示:

handleSubmit = (e) => {
    e.preventDefault();

    axios.post('http://localhost:3000/signup', {

      first_name: this.state.first_name,
      last_name: this.state.last_name,
      email: this.state.email,
      user_name: this.state.user_name,
      password: this.state.password,
      created_on: this.state.created_on,
      isSignedup: !this.state.isSignedup
    })
    .then(data => {
      console.log(data);
      this.props.history.replace('/login');
    })
    .catch(err => {
      console.log(err);
    })
  }

The error I keep receiving is that .then is not a function. 我一直收到的错误是.then不是函数。 Can someone please help me with this issue? 有人可以帮我解决这个问题吗? Thank you in advance. 先感谢您。

You are getting the error .then is not a function because of this code: 您遇到错误。由于以下代码,该.then is not a function

const user = {

  first_name: this.state.first_name,
  last_name: this.state.last_name,
  email: this.state.email,
  user_name: this.state.user_name,
  password: this.state.password,
  created_on: this.state.created_on,
  isSignedup: !this.state.isSignedup
}
.then

That's not valid javascript. 那不是有效的javascript。 Assigning an object to a variable does not create a promise. 将对象分配给变量不会创建承诺。 You have to actually call on signupUser . 您必须实际调用signupUser

Furthermore, I don't understand why you pass dispatch into your signup function if you are never calling on it? 此外,如果您从不调用调度功能,为什么不将它传递给注册函数,我也不明白?

You are on the right track with your thinking as it makes the design of your application a bit more modular. 您的思路正确,因为它使应用程序的设计更具模块化。

You could create a folder called apis/ , it doesn't have to be called that but I am just giving you an example. 您可以创建一个名为apis/的文件夹,而不必这样命名,但我仅举一个例子。 Then inside of there create a file called myjson.js , again call it what you think its best. 然后在其中创建一个名为myjson.js的文件,再次将其命名为您认为最好的文件。 Inside that folder you will have something like this: 在该文件夹内,您将具有以下内容:

import axios from "axios";

export default axios.create({
  baseURL: "https://api.myjson.com"
});

Then you could implement that inside your action creator as myJson.post() 然后,您可以在动作创建者内部将其实现为myJson.post()

You could also do something like this: 您还可以执行以下操作:

import React, { Component } from "react";
import axios from "axios";

const ROOT_URL =
  "https://exampleurl.com";

class SignUpForm extends Component {
  state = { phone: "" };

  handleSubmit = () => {
    axios
      .post(`${ROOT_URL}/createUser`, {
        phone: this.state.phone
      })
      .then(() => {
        axios.post(`${ROOT_URL}/requestOneTimePassword`, {
          phone: this.state.phone
        });
      });
  };

The above of course is based on a one time password type of authentication so tailor it to the logic of your architecture. 上面的课程当然是基于一次身份验证的密码类型,因此请根据您的体系结构的逻辑对其进行定制。

Also, if you are going to use a constructor function with super(props) you need to pass props into it like I just did. 另外,如果您要将constructor函数与super(props)一起使用,则需要像我刚才那样将props传递给它。

You can avoid all that by using ES7 and just assigning 您可以通过使用ES7并通过分配来避免所有这些情况

state = {
  first_name: '',
  last_name: '',
  user_name: '',
  email: '',
  password: '',
  created_on: date,
  isSignedup: false
}

You are already using an arrow function in your handleSubmit , so there is no need to do this: this.handleSubmit = this.handleSubmit.bind(this); 您已经在handleSubmit使用了箭头功能,因此无需这样做: this.handleSubmit = this.handleSubmit.bind(this); The arrow function is taking care of the context of this . 箭头功能正在采取的背景下照顾this

We can take it further and refactor that handleSubmit function to look cleaner by using ES7 async/await syntax like so: 我们可以更进一步,通过使用如下ES7 async / await语法来重构handleSubmit函数,使其看起来更整洁:

handleSubmit = async () => {
 await axios.post(`${ROOT_URL}/createUser`, {
   phone: this.state.phone
 });
 await axios.post(`${ROOT_URL}/requestOneTimePassword`, {
   phone: this.state.phone
 });
};

And to handle errors, since we are using async/await, we can wrap everything awaited with a try/catch block like so: 为了处理错误,由于我们使用的是异步/等待,我们可以使用try / catch块包装所有等待的内容,如下所示:

handleSubmit = async () => {
    try {
      await axios.post(`${ROOT_URL}/createUser`, {
        phone: this.state.phone
      });

      await axios.post(`${ROOT_URL}/requestOneTimePassword`, {
        phone: this.state.phone
      });
    } catch (err) {
      console.log(err);
    }
  };

So this way you can catch and console log the error. 这样,您就可以捕获并控制台记录错误。

And try/catch is not new with ES2015/16/17, its been around for awhile. 并且try / catch在ES2015 / 16/17中并不是新事物,已经存在了一段时间。

Essentially, whenever you want to handle errors thrown by a request managed by the await statement we can wrap it with try/catch statement. 本质上,每当您要处理由await语句管理的请求引发的错误时,我们都可以使用try / catch语句包装它。

The failed network request response will be passed in as the error object and we can console log it to see what happens. 失败的网络请求响应将作为错误对象传递,我们可以对其进行控制台日志以查看发生了什么。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Node.js:组织我的应用程序:在单独的文件中使用路由和模型,如何从路由中获取模型? - Node.js : organising my application : using routes and models in separate files, how can I get models from routes? 如何将某些Node.js文件放置在Node.js应用程序根文件夹之外? - How can I place some of my Node.js files outside of my Node.js application root folder? 如何使用 node.js 将 axios 响应发送到变量 - How I can send my axios response to a variable with node.js 我创建了我的 react 应用程序并与 electron.js 连接。 现在如何将我的后端从服务器文件夹与电子连接 - I create a build of my react app and connected with electron.js. now how to connect my backend from server folder with electron 如何将 API 分成不同的文件? (路由)Node.js + MySQL - How can I separate an API into diferent files? (routes) Node.js + MySQL Node.js和Express 4如何分开? - How to separate routes on Node.js and Express 4? 如何将我的所有资产(Html、JS、CSS、node.JS)放入反应中? - How can I put my all asset(Html, JS, CSS, node.JS) into the react? 如何将导入路由抽象到主 App.js - React,Node.js - How can I abstract importing routes to the main App.js - React, Node.js 如何构造/访问非node.js应用程序的react组件? - How can I structure/access the react components of my non node.js application? 我如何使用 adonis /node.js 中的模型实例创建 create() 方法? - How i can make a create() method using a instance of my model in adonis /node.js?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM