首页 > 解决方案 > React.js 阻塞标头

问题描述

我正在制作一个登录表单,当它提交时它应该调用我的后端 API,它可以工作,但我被重定向到我的 React 服务器。

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>

我的身份验证文件:

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;
  }
};

在提交时我被重定向到我的 React 服务器localhost:3000/login?p=ex&u=ex,而不是它应该调用我的服务器 APIlocalhost:9999/login

更新

对不起,我忘了在我的 api url 上添加 http,但现在我收到了这个错误:

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.

在此处输入图像描述

标签: javascriptreactjsaxios

解决方案


e.preventDefault()将阻止您的表单重新加载整个页面。看起来您的代码中已经包含此内容,但已被注释掉。

// e.preventDefault();


推荐阅读