简体   繁体   English

连接后端与前端时已释放连接错误

[英]Error of Connection already released while connecting backend with frontend

I connected my express backend with react frontend using axios.However i am getting an error of connection already released .I think there is due to the poor connection with backend.Hoping for help.我使用 axios 将我的快速后端与反应前端连接起来。但是我收到了一个connection already released错误。我认为这是由于与后端的连接不佳。希望得到帮助。

My express backend index.js has following code我的快递后端index.js有以下代码

const express = require('express')
const bodyParser = require('body-parser')

var cors = require('cors')

const mySql = require('mysql');

const app = express();
const PORT = process.env.PORT||5000

app.use(cors())
app.use(bodyParser.json())

//Database
const pool = mySql.createPool({
connectionLimit:100,
host:'localhost',
user:'root',
password:'',
database:'nodejsauthentication'
 })
 //Creating New Accounts
function createUser(req,res){
 if(req.body.Password === req.body.ConfirmPassword){
 pool.getConnection((err,connection)=>{
 if (err) throw err
 connection.query(`SELECT * FROM USERS WHERE email='${req.body.Email}'`,(errors,result)=>{
 connection.release();
 if(errors) {throw errors}
         
 if(result =="")
   {
    var sql = `INSERT INTO USERS (name,email,password) VALUES('${req.body.Name}','${req.body.Email}','${req.body.Password}')`
     connection.query(sql,(Err,response)=>{
     connection.release
     if(Err) throw Err
     res.send("Sucessfully created Account.LogIn to continue");
       })
      }
     else
      {
       res.send("Email is Already Taken");
       } 
     })
  })
}
else
{
 res.send("Passwords Don't Match.Try Again");
}    
 }
  //MiddleWare for logging In.
 function authenticate(req,res)
{
  pool.getConnection((err,connection)=>{
   if(err) throw err
    
   connection.query(`SELECT * FROM USERS WHERE email='${req.body.Email}'`,(err,result)=>{
   connection.release();

   if(err) throw err
   if(result == "")
   res.send("No user is associated with that email");
   else{
      connection.query(`SELECT * FROM USERS WHERE email='${req.body.Email}' AND password='${req.body.Password}'`,(err,result)=>{
       connection.release();
    
     if(err) throw err
      else{
       if(result == "")
        {
          res.send("Email or password Didnot Match");
         }
         else{
           res.send("Congratulations!!!")
            }
          }
       })
     }
   })      
 })
}
//requests
 app.get('/',(req,res)=>{
  res.send("At '/'");
  })

app.post('/home',authenticate,(req,res)=>{
  console.log("Recieved a post request");
  })

app.post('/createUser',createUser,(req,res)=>{
console.log("creating new Users");
 })

//listen to a server
app.listen(PORT,()=>{
console.log(`Server running sucessfully at port ${PORT}`)
 })

Here is what I have written in my frontend这是我在前端写的

import {React,Component } from 'react';
import axios from 'axios'
import './form.css';

export default class signIn extends Component{
constructor(props){
super(props);
this.state={
  Name:'',
  Email:'',
  Password:'',
  ConfirmPassword:'',
  Response:''
}
this.handleClick = this.handleClick.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleClick(e){
this.setState({
 [e.target.name]:e.target.value
})
}
handleSubmit(e){
console.log("Submitted");
axios.post('http://localhost:5000/createUser',{
Name:this.state.Name,
Email:this.state.Email,
Password:this.state.Password,
ConfirmPassword:this.state.ConfirmPassword
}).then((res)=>{
this.setState({
 Name:'',
 Email:'',
 Password:'',
 ConfirmPassword:'',
 Response:res.data
 })
})
}
render(){
return (
<div>
<h5 className="message">{this.state.Response}</h5>
<div className="contact">
<section className="cntct">
<form >
<input type="text" name="Name" placeholder="Enter Your Full Name" onChange={this.handleClick} value={this.state.Name} required/>
<input type="email" name="Email" placeholder="Email Address" onChange={this.handleClick} value={this.state.Email} required/>
<input type="password" name="Password" placeholder="Password" onChange={this.handleClick} value={this.state.Password} required/>
<input type="password" name="ConfirmPassword" placeholder="Confirm Password" onChange={this.handleClick} value={this.state.ConfirmPassword} required/>
<button type="button"className="logIn" onClick={this.handleSubmit}>Create Account</button>
</form>
</section>
</div>
</div>
 )
 }
}

In my debugging console I have these following error在我的调试控制台中,我有以下错误

Uncaught (in promise) Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:84)

You are releasing the SQL connection at line 5 of createUser before you do the insert在执行插入之前,您将在createUser的第 5 行释放 SQL 连接

function createUser(req,res){
 if(req.body.Password === req.body.ConfirmPassword){
 pool.getConnection((err,connection)=>{
 if (err) throw err
 connection.query(`SELECT * FROM USERS WHERE email='${req.body.Email}'`,(errors,result)=>{
// connection.release();
 if(errors) {throw errors}
         
 if(result =="")
   {
    var sql = `INSERT INTO USERS (name,email,password) VALUES('${req.body.Name}','${req.body.Email}','${req.body.Password}')`
     connection.query(sql,(Err,response)=>{
     connection.release
     if(Err) throw Err
     res.send("Sucessfully created Account.LogIn to continue");
       })
      }
     else
      {
       res.send("Email is Already Taken");
       } 
     })
  })
}
else

Also Add a catch to the promise to get a reason of the error.还要向 promise 添加一个 catch 以获取错误原因。

axios.post('http://localhost:5000/createUser',{
Name:this.state.Name,
Email:this.state.Email,
Password:this.state.Password,
ConfirmPassword:this.state.ConfirmPassword
}).then((res)=>{
this.setState({
 Name:'',
 Email:'',
 Password:'',
 ConfirmPassword:'',
 Response:res.data
 })
})
.catch(err => {
  // log the error
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM