我试图创建一个注册表单,使用node.js 连接到后端。它工作得很好,但现在我面临的问题是
Cannot set headers after they are sent to the client
当用户名正确时(即,实现results.length==0,而不是插入数据,它会给出错误。当我检查它时:
r.js:154 Uncaught (in promise) AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …} P
const cors=require("cors");
const { response } = require("express");
const express = require("express");
const app = express();
const mysql=require("mysql");
app.use(cors());
app.use(express.json());
const db=mysql.createConnection({
host: "localhost",
user: "root",
password:"password",
database:"ggsklogin",
});
app.post("/checkusersk",(req,res)=>{
const username=req.body.username;
const password=req.body.password;
db.query("select username from skcred where username=?;",[username],
(err,results)=>{
res.send(results);
if(err){
res.send({err});
}
if(results.length>0){
res.send({message:"username exists"});
}
if(results.length==0){
res.send({message:"done"});
db.query("insert into skcred(username,password) values(?,?)",[username,password],
);
}
});
});
我的前端代码:
import React, { Fragment } from 'react';
import { useState,useEffect} from 'react';
import axios from 'axios';
import ReactSearchBox from "react-search-box";
import { connect } from 'react-redux';
import { key } from 'localforage';
import { Alert } from 'bootstrap';
import { useNavigate } from 'react-router-dom';
function Newlogin() {
const navigate=useNavigate()
const[usernamea,setusername]=useState('')
const[passworda,setpassword]=useState('')
const[repeatpass,setreapeatpass]=useState('')
const[loginstatus,setLoginstatus]=useState('')
const check=()=>{
axios.post('http://localhost:3001/checkusersk', {
username: usernamea,
password: passworda,
}).then((response)=>{
if(response.data){
console.log(response.data)
setLoginstatus(response.data.message);
}
if(response.data=0) {
navigate('/sk-details')
}
})
}
if(loginstatus=='done'){
navigate('/sk-details')
}
const passwordcheck=(e)=>{
if(passworda!=repeatpass){
setLoginstatus("password mismatch")
}
check()
}
return (
<div>
<div>
<input type="text" placeholder='enter username' name='username' onChange={(e)=>{setusername(e.target.value)}}/>
<br/>
<br/>
<input type="password" placeholder='enter password' name='password' onChange={(e)=>{setpassword(e.target.value)}}/>
<br/>
<br/>
<input text="password" placeholder='repeat password' name='repeatpass' onChange={(e)=>{setreapeatpass(e.target.value)}}/>
<br/>
<br/>
<button onClick={passwordcheck}></button>
</div>
<div class="alert alert-info" role="alert">
{loginstatus}
</div>
</div>
);
}
export default Newlogin;
我也期待你们提供另一个解决方案。也就是说在前端,如果用户名是唯一的并且密码匹配,则应该重定向到“/sk-details”。请给我一个解决方案。
在第一种情况下,我尝试显示结果,但它给出了未捕获的 inpromise 错误。 在第二种情况下,当用户名和密码正确时,它不会被重定向!
最佳答案
错误位于 res.send(results);
行,您正在发送此响应,当您所说的 results.length==0
为 true 时,它会尝试发送另一个响应 res.send({message:"done"})
,该响应会失败,因为您无法从单个端点 .send
多个响应。如果您需要发送结果
,那么您需要另一个条件逻辑,但如果您不想发送它,请将其删除:
const cors=require("cors");
const { response } = require("express");
const express = require("express");
const app = express();
const mysql=require("mysql");
app.use(cors());
app.use(express.json());
const db=mysql.createConnection({
host: "localhost",
user: "root",
password:"password",
database:"ggsklogin",
});
app.post("/checkusersk",(req,res)=>{
const username=req.body.username;
const password=req.body.password;
db.query("select username from skcred where username=?;",[username],
(err,results)=>{
// res.send(results); // this is removed so that below conditions can send response
if(err){
res.send({err});
}
if(results.length>0){
res.send({message:"username exists"});
}
if(results.length==0){
res.send({message:"done"});
db.query("insert into skcred(username,password) values(?,?)",[username,password],
);
}
});
});
与您的后端错误无关,前端的 Axios 设置为失败,您正在分配 = 值而不是使用比较 == 行 if(response.data=0) {
= 运算符,但即便如此,您也会将对象与 0
进行比较,而 0
始终为 false
,相反,您想要检查 response.data === 'done'
,修复它:
// ...
const check=()=>{
axios.post('http://localhost:3001/checkusersk', {
username: usernamea,
password: passworda,
}).then((response)=>{
if(response.data){
console.log(response.data)
setLoginstatus(response.data.message);
}
// if(response.data=0) { // This would always be false
// Use this instead:
if (response.data === 'done') {
navigate('/sk-details')
}
})
}
// ...
关于mysql - 我在连接到 mysql 的 Node js 中收到错误 "Cannot set headers after they are sent to the client",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76069293/