草庐IT

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

codeneng 2023-03-28 原文

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();,因此处理程序一旦解决就会给出该错误。

  • 好的谢谢 !知道为什么它不重定向页面吗?
  • 无需在服务器端重定向。您可以使用 history react-router 做出反应
  • 这将如何完成?有没有这样的例子?如果可能的话,在服务器端进行重定向是否符合我的逻辑
  • response.redirect() 应该重定向。检查网络选项卡中的响应
  • fetch("/auth", { 它说这是登录页面中的错误原因
  • 参考这个:stackoverflow.com/questions/39735496/…

有关关于sql:React登录表单抛出错误\\”Cannot set headers after they are sent to the client\\”的更多相关文章

  1. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  2. ruby - 如何在 Rails 4 中使用表单对象之前的验证回调? - 2

    我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser

  3. ruby - 在 Ruby 中重新分配常量时抛出异常? - 2

    我早就知道Ruby中的“常量”(即大写的变量名)不是真正常量。与其他编程语言一样,对对象的引用是唯一存储在变量/常量中的东西。(侧边栏:Ruby确实具有“卡住”引用对象不被修改的功能,据我所知,许多其他语言都没有提供这种功能。)所以这是我的问题:当您将一个值重新分配给常量时,您会收到如下警告:>>FOO='bar'=>"bar">>FOO='baz'(irb):2:warning:alreadyinitializedconstantFOO=>"baz"有没有办法强制Ruby抛出异常而不是打印警告?很难弄清楚为什么有时会发生重新分配。 最佳答案

  4. Hive SQL 五大经典面试题 - 2

    目录第1题连续问题分析:解法:第2题分组问题分析:解法:第3题间隔连续问题分析:解法:第4题打折日期交叉问题分析:解法:第5题同时在线问题分析:解法:第1题连续问题如下数据为蚂蚁森林中用户领取的减少碳排放量iddtlowcarbon10012021-12-1212310022021-12-124510012021-12-134310012021-12-134510012021-12-132310022021-12-144510012021-12-1423010022021-12-154510012021-12-1523.......找出连续3天及以上减少碳排放量在100以上的用户分析:遇到这类

  5. sql - 查询忽略时间戳日期的时间范围 - 2

    我正在尝试查询我的Rails数据库(Postgres)中的购买表,我想查询时间范围。例如,我想知道在所有日期的下午2点到3点之间进行了多少次购买。此表中有一个created_at列,但我不知道如何在不搜索特定日期的情况下完成此操作。我试过:Purchases.where("created_atBETWEEN?and?",Time.now-1.hour,Time.now)但这最终只会搜索今天与那些时间的日期。 最佳答案 您需要使用PostgreSQL'sdate_part/extractfunction从created_at中提取小时

  6. ruby-on-rails - 关于 Ruby 的一般问题 - 2

    我在我的rails应用程序中安装了来自github.com的acts_as_versioned插件,但有一段代码我不完全理解,我希望有人能帮我解决这个问题class_eval我知道block内的方法(或任何它是什么)被定义为类内的实例方法,但我在插件的任何地方都找不到定义为常量的CLASS_METHODS,而且我也不确定是什么here,并且有问题的代码从lib/acts_as_versioned.rb的第199行开始。如果有人愿意告诉我这里的内幕,我将不胜感激。谢谢-C 最佳答案 这是一个异端。http://en.wikipedia

  7. ruby-on-rails - Rails - Carrierwave 进程抛出 ArgumentError : no images in this image list - 2

    在尝试实现应用auto_orient的过程之后!对于我的图片,我收到此错误:ArgumentError(noimagesinthisimagelist):app/uploaders/image_uploader.rb:36:in`fix_exif_rotation'app/controllers/posts_controller.rb:12:in`create'Carrierwave在没有进程的情况下工作正常,但在添加进程后尝试上传图像时抛出错误。流程如下:process:fix_exif_rotationdeffix_exif_rotationmanipulate!do|image|

  8. sql - 在 Rails Console for PostgreSQL 的表中显示数据 - 2

    我找到了这样的东西:Rails:Howtolistdatabasetables/objectsusingtheRailsconsole?这一行没问题:ActiveRecord::Base.connection.tables并返回所有表但是ActiveRecord::Base.connection.table_structure("users")产生错误:ActiveRecord::Base.connection.table_structure("projects")我认为table_structure不是Postgres方法。如何列出Postgres数据库的Rails控制台中表中的所有

  9. ruby-on-rails - Ruby 长时间运行的进程对队列事件使用react - 2

    我有一个将某些事件写入队列的Rails3应用。现在我想在服务器上创建一个服务,每x秒轮询一次队列,并按计划执行其他任务。除了创建ruby​​脚本并通过cron作业运行它之外,还有其他稳定的替代方案吗? 最佳答案 尽管启动基于Rails的持久任务是一种选择,但您可能希望查看更有序的系统,例如delayed_job或Starling管理您的工作量。我建议不要在cron中运行某些东西,因为启动整个Rails堆栈的开销可能很大。每隔几秒运行一次它是不切实际的,因为Rails上的启动时间通常为5-15秒,具体取决于您的硬件。不过,每天这样做几

  10. ruby - 防止SQL注入(inject)/好的Ruby方法 - 2

    Ruby中防止SQL注入(inject)的好方法是什么? 最佳答案 直接使用ruby?使用准备好的语句:require'mysql'db=Mysql.new('localhost','user','password','database')statement=db.prepare"SELECT*FROMtableWHEREfield=?"statement.execute'value'statement.fetchstatement.close 关于ruby-防止SQL注入(inject

随机推荐