首页 > 解决方案 > React 登录表单抛出错误“发送到客户端后无法设置标题”

问题描述

嗨,我正在制作一个完整的堆栈登录表单。我收到的错误是“:在将标头发送到客户端后无法设置标头”,请参阅底部的完整日志。

我要做的就是创建一个登录表单,它将我重定向到主页,然后我可以在其中开始处理 jwt 令牌。

知道为什么会这样吗?有关如何使此表格充分发挥作用的任何建议?

感谢你的帮助 :)


app.post("/auth", function(req, response) {
  sql.connect(config, function(err) {
    if (err) {
      console.log(err + "initial connection");
      console.log(config.server);
    } else {
      try {
        var request = new sql.Request();

        var body = req.body;

        //console.log(body);

        var email = body.email;
        var password = body.password;

        console.log(email, password);

        try {
          request.input("email", sql.VarChar, email);
          request.input("password", sql.VarChar, password);
          request.query(
            "SELECT * FROM TestLogin WHERE email = 'email' AND password = 'password'",

            function(error, results, fields) {
              if (results.length > 0) {
                req.session.loggedin = true;
                req.session.email = email;
                response.redirect("/home");
              } else {
                response.send("Incorrect email and/or Password!");
              }
              response.end();
            }
          );

          response.send("Please enter email and Password!");
          response.end();
        } catch (e) {
          console.log(e);
          response.status(400);
          response.send(e);
        }
      } catch (e) {
        console.log(e);
        response.status(400);
        response.send(e);
      }
    }
  });
});

登录类

class Login extends React.Component {
  constructor() {
    super();

    this.state = { email: "", password: "" };
    this.onSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(e) {
    e.preventDefault();
    if (this.state.email.length < 8 || this.state.password.length < 8) {
      alert(`please enter the form correctly `);
    } else {
      const data = { email: this.state.email, password: this.state.password };

      fetch("/auth", {
        method: "POST", // or 'PUT'
        headers: {
          Accept: "application/json, text/plain, */*",
          "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
      })
        .then(response => response.json())
        .then(data => {
          console.log("Success:", data);
        })
        .catch(error => {
          console.error("Error:", error);
        });
    }
  }
  catch(e) {
    console.log(e);
  }

  render() {
    console.log(this.state.email);
    console.log(this.state.password);
    return (
      <div>
        <Formik
          class="form-signin"
          action="auth"
          method="POST"
          initialValues={{ email: "", password: "" }}
          onSubmit={(values, { setSubmitting }) => {
            setTimeout(() => {
              console.log("Logging in", values);
              setSubmitting(false);
            }, 500);
          }}
          validationSchema={Yup.object().shape({
            email: Yup.string()
              .email()
              .required("Required")
              .matches(
                /(?=.*codestone)/,
                "This is not a Codestone email address."
              ),

            password: Yup.string()
              .required("No password provided.")
              .min(8, "Password is too short - should be 8 chars minimum.")
              .matches(/(?=.*[0-9])/, "Password must contain a number.")
          })}
        >
          {props => {
            const {
              values,
              touched,
              errors,
              isSubmitting,
              handleChange,
              handleBlur,
              handleSubmit
            } = props;

            return (
              <form
                onSubmit={handleSubmit}
                class="form-signin"
                action="auth"
                method="POST"
              >
                <div className="jumbotron">
                  <h2>Login </h2>
                  <div className="help">
                    <Popup trigger={<Link> Help?</Link>} className="center">
                      <div>
                        Enter Codestone Email address and Password connected to
                        the account.
                      </div>
                    </Popup>
                  </div>

                  <label htmlFor="email">Email</label>

                  <input
                    name="email"
                    type="email"
                    placeholder="Enter your email"
                    value1={values.email}
                    value={this.state.email}
                    onInput={handleChange}
                    onChange={e => this.setState({ email: e.target.value })}
                    onBlur={handleBlur}
                    className={errors.email && touched.email && "error"}
                  />
                  {errors.email && touched.email && (
                    <div className="input-feedback">{errors.email}</div>
                  )}
                  <label htmlFor="email">Password</label>
                  <input
                    name="password"
                    type="password"
                    placeholder="Enter your password"
                    value2={values.password}
                    value={this.state.password}
                    onInput={handleChange}
                    onChange={e => this.setState({ password: e.target.value })}
                    onBlur={handleBlur}
                    className={errors.password && touched.password && "error"}
                  />
                  {errors.password && touched.password && (
                    <div className="input-feedback">{errors.password} </div>
                  )}

                  <button class="button" type="submit" onClick={this.onSubmit}>
                    Login
                  </button>
                  <p>
                    <Link to="/login"> Login Page </Link>
                  </p>
                  <p>
                    <Link to="/reset"> Reset Password </Link>
                  </p>
                </div>
              </form>
            );
          }}
        </Formik>
      </div>
    );
  }
}

错误

undefined undefined
[0] _http_outgoing.js:535
[0]     throw new ERR_HTTP_HEADERS_SENT('set');
[0]     ^
[0]
[0] Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
[0]     at ServerResponse.setHeader (_http_outgoing.js:535:11)
[0]     at ServerResponse.header (C:\Users\Henry Peters\Desktop\Vault\Newfolder(3)\Codestone-Desk-branch1\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (C:\Users\Henry Peters\Desktop\Vault\Newfolder(3)\Codestone-Desk-branch1\node_modules\express\lib\response.js:170:12)
[0]     at C:\Users\Henry Peters\Desktop\Vault\Newfolder(3)\Codestone-Desk-branch1\server.js:183:26
[0]     at C:\Users\Henry Peters\Desktop\Vault\Newfolder(3)\Codestone-Desk-branch1\node_modules\mssql\lib\base\request.js:395:9
[0]     at Request.userCallback (C:\Users\Henry Peters\Desktop\Vault\Newfolder(3)\Codestone-Desk-branch1\node_modules\mssql\lib\tedious\request.js:471:15)
[0]     at Request.callback (C:\Users\Henry Peters\Desktop\Vault\Newfolder(3)\Codestone-Desk-branch1\node_modules\tedious\lib\request.js:56:14)
[0]     at Connection.endOfMessageMarkerReceived (C:\Users\Henry Peters\Desktop\Vault\Newfolder(3)\Codestone-Desk-branch1\node_modules\tedious\lib\connection.js:2402:20)
[0]     at Connection.dispatchEvent (C:\Users\Henry Peters\Desktop\Vault\Newfolder(3)\Codestone-Desk-branch1\node_modules\tedious\lib\connection.js:1274:15)
[0]     at Parser.<anonymous> (C:\Users\Henry Peters\Desktop\Vault\Newfolder(3)\Codestone-Desk-branch1\node_modules\tedious\lib\connection.js:1067:14) {
[0]   code: 'ERR_HTTP_HEADERS_SENT'

建议更改后更新。这仍然不会将用户重定向到 hpome 页面,甚至不会显示任何登录用户的迹象。控制台或使用 chrome 开发工具时不会显示任何错误。可以的话请指教


app.post("/auth", function(req, response) {
  sql.connect(config, function(err) {
    if (err) {
      console.log(err + "initial connection");
      console.log(config.server);
    } else {
      try {
        var request = new sql.Request();

        var body = req.body;

        //console.log(body);

        var Email = body.email;
        var Password = body.password;

        //console.log(email, password);

        try {
          request.input("email", sql.VarChar, Email);
          request.input("password", sql.VarChar, Password);
          request.query(
            "SELECT * FROM TestLogin WHERE email = Email AND password = Password",

            function(error, results, fields) {
              if (results.length > 0) {
                req.session.loggedin = true;
                req.session.email = email;
                response.redirect("/home");
              } else if (results.length < 0) {
                response.send("Incorrect email and/or Password!");
              }
            }
          );

          // response.send("Please enter email and Password!");
          // response.end();
        } catch (e) {
          console.log(e);
          response.status(400);
          response.send(e);
        }
      } catch (e) {
        console.log(e);
        response.status(400);
        response.send(e);
      }
    }
  });
});

标签: sqlnode.jssql-serverreactjsexpress

解决方案


     try {
          request.input("email", sql.VarChar, email);
          request.input("password", sql.VarChar, password);
          request.query(
            "SELECT * FROM TestLogin WHERE email = 'email' AND password = 
           'password'",

            function(error, results, fields) {
              if (results.length > 0) {
                req.session.loggedin = true;
                req.session.email = email;
                response.redirect("/home");
              } else {
                response.send("Incorrect email and/or Password!");
              }
              response.end();
            }
          );

          //response.send("Please enter email and Password!");
          //response.end();

响应结束response.send("Please enter email and Password!");response.end();,因此处理程序一旦解决就会给出该错误。


推荐阅读