关于sql:React登录表单抛出错误\\”Cannot set headers after they are sent to the client\\”

React Login form throws error "Cannot set headers after they are sent to the client"

您好,我正在制作一个完整的堆栈登录表单。我收到的错误是 ": Cannot set headers after they are sent to the client" 请参阅底部的完整日志。

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

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

感谢您的帮助:)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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);
      }
    }
  });
});

登录类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
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 (
     
        <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"
              >
               
                  Login
                 
                    <Popup TRIGGER={<Link> Help?</Link>} className="center">
                     
                        Enter Codestone Email address AND Password connected TO
                        the account.
                     
                    </Popup>
                 

                  <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 && (
                    {errors.email}
                  )}
                  <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 && (
                    {errors.password}
                  )}

                  <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>
               
              </form>
            );
          }}
        </Formik>
     
    );
  }
}

错误

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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\
ewfolder(3)\\Codestone-Desk-branch1\
ode_modules\\express\\lib\
esponse.js:771:10)
    at ServerResponse.send (C:\\Users\\Henry Peters\\Desktop\\Vault\
ewfolder(3)\\Codestone-Desk-branch1\
ode_modules\\express\\lib\
esponse.js:170:12)
[0]     at C:\\Users\\Henry Peters\\Desktop\\Vault\
ewfolder(3)\\Codestone-Desk-branch1\\server.js:183:26
[0]     at C:\\Users\\Henry Peters\\Desktop\\Vault\
ewfolder(3)\\Codestone-Desk-branch1\
ode_modules\\mssql\\lib\\base\
equest.js:395:9
[0]     at Request.userCallback (C:\\Users\\Henry Peters\\Desktop\\Vault\
ewfolder(3)\\Codestone-Desk-branch1\
ode_modules\\mssql\\lib\\tedious\
equest.js:471:15)
[0]     at Request.callback (C:\\Users\\Henry Peters\\Desktop\\Vault\
ewfolder(3)\\Codestone-Desk-branch1\
ode_modules\\tedious\\lib\
equest.js:56:14)
[0]     at Connection.endOfMessageMarkerReceived (C:\\Users\\Henry Peters\\Desktop\\Vault\
ewfolder(3)\\Codestone-Desk-branch1\
ode_modules\\tedious\\lib\\connection.js:2402:20)
[0]     at Connection.dispatchEvent (C:\\Users\\Henry Peters\\Desktop\\Vault\
ewfolder(3)\\Codestone-Desk-branch1\
ode_modules\\tedious\\lib\\connection.js:1274:15)
[0]     at Parser. (C:\\Users\\Henry Peters\\Desktop\\Vault\
ewfolder(3)\\Codestone-Desk-branch1\
ode_modules\\tedious\\lib\\connection.js:1067:14) {
[0]   code: 'ERR_HTTP_HEADERS_SENT'

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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);
      }
    }
  });
});

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
     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();,因此处理程序一旦解决就会给出该错误。