ricemilk
ricemilk

Reputation: 85

How to connect react js with node js?

So I have a login/register function in node js that is using mongoose, express and JWT and it's working. And I also have a login and regiser forms in react. And I don't know how to make it that, if I enter the data in the form, it gets registered in the back-end code.

I have react running on port 3000 and express onn port 4000.

And I've tried using cors and axios, but I can't seem to really understand how they work.

Upvotes: 0

Views: 81

Answers (1)

ricemilk
ricemilk

Reputation: 85

So after looking at similar examples, I found out that you need to use cors with axios to achieve it. Here is my register form code for react.

import React, { useState } from "react";
import {
  Container,
  FormWrap,
  Icon,
  FormContent,
  Form,
  FormH1,
  FormLabel,
  FormInput,
  FormButton,
  Text,
} from "./SignupElements";
import axios from "axios";

const Signup = () => {
  const [registerUsername, setRegisterUsername] = useState("");
  const [registerPassword, setRegisterPassword] = useState("");
  const [registerEmail, setRegisterEmail] = useState("");

const register = () => {
    axios({
      method: "POST",
      data: {
        username: registerUsername,
        password: registerPassword,
        email : registerEmail,
      },
      withCredentials: true,
      url: "http://localhost:4000/user/signup",
    }).then((res) => console.log(res));
};


  return (
    <Container>
      <FormWrap>
        <Icon to="/">Amp Beats</Icon>
        <FormContent>
          <Form>
            <FormH1>Create an account</FormH1>
            <FormLabel htmlFor="for">Email</FormLabel>
            <FormInput
              type="email"
              onChange={(e) => setRegisterEmail(e.target.value)}
            ></FormInput>
            <FormLabel htmlFor="for">Username</FormLabel>
            <FormInput
              type="username"
              onChange={(e) => setRegisterUsername(e.target.value)}
            ></FormInput>
            <FormLabel htmlFor="for">Password</FormLabel>
            <FormInput
              type="password"
              onChange={(e) => setRegisterPassword(e.target.value)}
            ></FormInput>
            <FormButton type="submit" onClick={register}>
              Create Accout
            </FormButton>
            <Text>
              WARNING: This is just a test.
            </Text>
          </Form>
        </FormContent>
      </FormWrap>
    </Container>
  );
};

export default Signup;

And the back end code is too complicated, but basically you just have to require('cors') and make the app use cors. I'm bad at explainig so here's the code:

app.use(
  cors({
    origin: "http://localhost:3000", // <-- the react app url
    credentials: true,
  })
);

Thought I would post this answer in case anyone has the same problem.

Upvotes: 1

Related Questions