chai.request()的回调使我抛出ECONNREFUSED

时间:2019-06-04 15:04:40

标签: node.js express mocha chai

我正在尝试使用mocha和chai测试位于app.js中的快速查询。但是,即使服务器在运行时运行正常,该回调也会引发ECONNREFUSED错误。

const chai = require('chai');
const chaiHttp = require('chai-http');
const { expect } = require('chai');
const app = require('../app');
const should = require("chai").should();
chai.use(chaiHttp);

describe("Login", () => {
    it("should return error when no login data", (done) => {
        chai.request(app)
            .post('/login')
            .end((error, results) => {
                if (error) throw error;
                should.exist(results);
                results.should.have.status(404);
                done();
            });
    });
});

完整错误-> 错误:连接ECONNREFUSED 127.0.0.1:3000     在TCPConnectWrap.afterConnect上[作为oncomplete](net.js:1113:14)

app.js中的相关代码

const express = require('express');
const mysql = require("mysql");
const app = express();
const bodyParser = require("body-parser");
const bcrypt = require("bcrypt");
const saltRounds = 10;
const session = require("express-session");
const cors = require("cors");
const multer = require("multer");
const upload = multer({dest:"uploads/"});
const http = require("http");
const socketIO = require('socket.io');


app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cors());
app.use(session({
   secret:"",
   resave:true,
   saveUninitialized: true
}));
app.use("/uploads",express.static("uploads"));
let con = mysql.createConnection({
//not empty in my real code 
   host:"",
   user: "",
   password: "",
   database: ""
});
let sess;

app.post("/login",function(req, res){
   con.query("SELECT username FROM user WHERE username = ?",[req.body.username],function (error,results) {
      if(results.length===0){
         res.redirect("http://localhost:3000/loginFailed");
         return res.status(404);
      }
      else{
         con.query("SELECT password FROM user WHERE username = ?",[req.body.username],
             function(error, results){
                if (error) throw error;
                console.log(results,req.body.password);
                if (bcrypt.compareSync(req.body.password, results[0].password)){
                   req.session.user = req.body.username;
                   req.session.admin = true;
                   console.log("00000");
                   sess = req.session;
                   console.log(sess.user);
                   res.redirect("http://localhost:3000/home");
                }
                else{
                   console.log("NOT OK2");
                   res.redirect("http://localhost:3000/loginFailed")
                }
             });
         }
      });
   });
server.listen(3001, function(){
});
module.exports = app;

0 个答案:

没有答案