0

I'm making a login form that when it submits it should call my back end API, it works but I get redirected to my React server.

onSubmit = e => {
    Auth.authenticate(this.state.formFields);
    // e.preventDefault();
  };

<div className="grid-container">
        <center>
          <form className="card" onSubmit={this.onSubmit}>
            <span className="title">Login</span>
            <InputFields
              onChange={this.onChange}
              username={this.state.formFields.u}
              password={this.state.formFields.p}
            />
            <button className="submit-button">
              <FontAwesomeIcon icon={faChevronRight} />
            </button>
          </form>
        </center>
      </div>

My authentication file:

const Auth = {
  isAuthenticated: false,
  authenticate(formFields) {
    axios
      .post("192.168.254.105:9999/login", { formFields })
      .then(response => {
        console.log(response);
        if (response.isAuthenticated == true) {
          this.isAuthenticated = response.isAuthenticated;
        }
      })
      .catch(error => console.log(error));
  },
  signout() {
    this.isAuthenticated = false;
  },
  getAuth() {
    return this.isAuthenticated;
  }
};

on submit I get redirected to my React server localhost:3000/login?p=ex&u=ex instead it should call my server API on localhost:9999/login

Update

Sorry my bad I forgot to add http on my api url, but now I get this error:

Access to XMLHttpRequest at 'http://192.168.254.105:9999/api/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

enter image description here

1
  • Since you turned the fix into a comment, the form still gets also submitted the regular way, which without method or action attributes defaults to GET and the current URL. Commented Feb 8, 2020 at 12:52

1 Answer 1

1

e.preventDefault() will stop your form from re-loading the entire page. It looks like you already have this in your code but it's commented out.

// e.preventDefault();

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

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.