React+Node.js+MySQL查询无数据返回,用户名校验功能异常求助
问题:MySQL+Node.js后端无法校验用户名是否存在
需求是校验数据库中指定用户名是否存在:不存在返回'done',存在则返回提示,但当前查询无数据返回,结果始终为[],无法完成校验。
Node.js后端代码
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.usernamea; db.query("select username from skcred where username=username;", (err,results)=>{ if(err){ res.send({err}); } if(results.length>0){ res.send(results); } else{ res.send({message:"done"}); } }); }); app.listen(3001,()=>{ console.log("running on 3001") });
React前端代码(newlogin.jsx)
import React, { Fragment } from 'react'; import { useState,useNavigate,useEffect} from 'react'; import axios from 'axios'; function Newlogin() { const[usernamea,setusername]=useState('') const[password,setpassword]=useState('') const[repeatpass,setreapeatpass]=useState('') const[loginstatus,setLoginstatus]=useState('') const check=()=>{ axios.post('http://localhost:3001/checkusersk', { username: usernamea, }).then((response)=>{ if(response.data){ setLoginstatus(response.data.message);} else{ setLoginstatus(response.data[0].username) } }) } return ( <div> <div> <input type="text" placeholder='enter username' name='username' onChange={(e)=>{setusername(e.target.value)}}/> <input type="password" placeholder='enter password' name='password' onChange={(e)=>{setpassword(e.target.value)}}/> <input text="password" placeholder='repeat password' name='repeatpass' onChange={(e)=>{setreapeatpass(e.target.value)}}/> <button onClick={check}></button> </div> <div> <h5>{loginstatus}</h5> </div> </div> ); } export default Newlogin;
MySQL数据库数据
select * from skcred; +--------------+----------+ | username | password | +--------------+----------+ | asadasasd | dsaad | | asdd | dasd | | asdd | dasd | | sada | ads | | sada | ads | | sada | ads | | sada | ads | | sada | ads | | sada | ads | | sada | ads | | sdaaaaaaaaaa | aaaa | | abiinaya | sridhar1 | | abinayaa | assf | | abinayaa | assf | | asdf | asdf | | asdf | asdf | | asdf | asdf | | assa | werr | | dddddd | ddddd | +--------------+----------+
问题排查与修复
1. 后端核心错误
- 参数名不匹配:前端传递的参数是
username,但后端用req.body.usernamea接收,导致无法获取到用户输入的用户名。 - SQL逻辑错误:
select username from skcred where username=username;是字段自匹配,会返回所有非空username的记录,但实际需要匹配前端传入的变量,且未使用参数化查询,导致逻辑完全失效。
修复后的后端代码
const cors=require("cors"); 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; // 使用参数化查询,避免SQL注入并正确传递变量 db.query("select username from skcred where username = ?;", [username], (err,results)=>{ if(err){ return res.status(500).send({error: err.message}); } if(results.length>0){ // 存在时返回明确提示 res.send({message: `用户名 ${results[0].username} 已存在`}); } else{ res.send({message:"done"}); } }); }); app.listen(3001,()=>{ console.log("running on 3001") });
2. 前端逻辑错误
前端判断条件if(response.data)永远为真(后端始终返回对象),导致无论用户名是否存在,都会显示'done'。
修复后的前端代码
import React from 'react'; import { useState} from 'react'; import axios from 'axios'; function Newlogin() { const[usernamea,setusername]=useState('') const[password,setpassword]=useState('') const[repeatpass,setreapeatpass]=useState('') const[loginstatus,setLoginstatus]=useState('') const check=()=>{ axios.post('http://localhost:3001/checkusersk', { username: usernamea, }).then((response)=>{ // 直接渲染后端返回的提示信息 setLoginstatus(response.data.message); }).catch(err => { // 处理请求失败的情况 setLoginstatus('校验失败,请重试'); console.error(err); }) } return ( <div> <div> <input type="text" placeholder='enter username' name='username' onChange={(e)=>{setusername(e.target.value)}}/> <input type="password" placeholder='enter password' name='password' onChange={(e)=>{setpassword(e.target.value)}}/> {/* 修正input类型为password */} <input type="password" placeholder='repeat password' name='repeatpass' onChange={(e)=>{setreapeatpass(e.target.value)}}/> {/* 添加按钮文字,提升用户体验 */} <button onClick={check}>校验用户名</button> </div> <div> <h5>{loginstatus}</h5> </div> </div> ); } export default Newlogin;
额外优化建议
- 坚持使用参数化查询,避免SQL注入风险。
- 增加错误捕获逻辑,处理网络请求或数据库查询失败的场景。
- 完善前端表单的基础校验(如用户名不能为空)。
内容的提问来源于stack exchange,提问作者DHARSHINI S
相关产品推荐
相关产品推荐

