Postman is stuck at a "GET" request, giving error that "Could not get response Error: read ECONNRESET" in Node JS using PostgreSQL as backend

Postman is stuck at a "GET" request, giving error that "Could not get response Error: read ECONNRESET" in Node JS using PostgreSQL as backend

我正在观看有关使用 JWT 令牌进行登录身份验证的视频教程。

我在 PostgreSQL 上构建了一个数据库,将其连接到我的 Node JS 服务器并测试了注册和登录命令。这两个查询在 Postman 上运行良好,并且 Postman 返回了预期的结果。

现在,在登录时,我在返回值中得到了一个JWT Token,它将进一步用于获取登录的用户ID及其信息。

因此,为了测试该令牌是否有效,我制作了一条路线来验证用户是否已登录。 (添加在登录和注册路由所在的同一个文件中)

此路由文件文件代码如下(jwAuth.js)。 我没有在里面添加注册码和登录码

const router = require('express').Router() 
const pool = require("../db")
const bcrypt = require("bcryptjs");
const jwtGenerator = require('../utils/jwtGenerator');
const authorization = require('../middleware/authorization');
// Registeration and Login Routes
// Verification Route 
router.get("/is-verify", authorization, async (res, req) => {
    try {
        res.json(true); 
        
    } catch (err) {
         console.log(err.message); 
        res.status(500).send("Server Error")
    }
})
module.exports = router;

中间件authorization.js的代码如下,

const jwt = require("jsonwebtoken");
require("dotenv").config();
module.exports = async (req, res, next) => {
    try {

        const jwtToken = req.header("token");

        if (!jwtToken) {
            return res.status(403).json("Not Authorized");
        }

        // In case we do have a token, check if the token is valid or not 
        const payload = jwt.verify(jwtToken, process.env.jwtSecret);

        req.user = payload.user; 


    } catch (err) {
        console.log(err.message); 
        return res.status(403).json("You are not authorized");
    }
}

我也在另一条路线上尝试了同样的事情,dashboard.js 应该 return/print 使用给它的 JWT 令牌的用户的 ID,条件是用户已正确登录

dashboard.js的代码如下,

const router = require('express').Router()
const pool = require("../db")
const authorization = require("../middleware/authorization")

router.get("/", authorization, async (req, res) => {
    try {
        res.json(req.user); 
    } catch (err) {
        console.log(err.message)
        res.status(500).json("Server Error"); 
    }
})


module.exports = router

而我的index.js(或server.js)的代码如下,

const express = require('express')
const app = express() 
const cors = require('cors')

app.use(express.json()) // Lets you use req.body 
app.use(cors())

// ROUTES 

// Register and Login Routes 

app.use("/auth", require("./routes/jwAuth"));
app.use("/dashboard", require("./routes/dashboard"));


app.listen(3000, () => {
    console.log("Console is running");
})

我的问题是,如果我尝试使用所需数据向以下链接发送请求,Postman 工作正常并且数据也添加到我的数据库中(并且在检查登录时也被正确检索)

http://localhost:3000/auth/register
http://localhost:3000/auth/login

但是当我用这个 URL 尝试同样的事情时(通过在邮递员 GET 请求的 Header 中提供 JWT 令牌,

http://localhost:3000/dashboard
http://localhost:3000/auth/is-verify

Postman 卡住了,处理请求的时间很长,最终报错,

无法得到回应 错误:读取 ECONNRESET

我试着搜索这个错误,显然这个问题的解决方法是在 etc/hosts 文件中添加本地主机的 IP 地址,但在那种情况下,我的注册和login POST Requests 也不会起作用。我无法解决问题,请有人帮忙。

可以肯定的是,我还在 etc/hosts 文件下方共享了 Registration/Login 路由以及 jwtGenerator 文件

etc/hosts 文件

# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

# localhost name resolution is handled within DNS itself.
#   127.0.0.1       localhost
#   ::1             localhost

0.0.0.0 hss.hsselite.com
0.0.0.0 www.hss.hsselite.com
0.0.0.0 d1v9mrqde8r3oj.cloudfront.net
0.0.0.0 www.d1v9mrqde8r3oj.cloudfront.net
0.0.0.0 api.hsselite.com
0.0.0.0 www.api.hsselite.com
0.0.0.0 hsselite.com/trial/step2.php
0.0.0.0 www.hsselite.com/trial/step2.php
0.0.0.0 anchorfree.com
0.0.0.0 www.anchorfree.com
0.0.0.0 box.anchorfree.net
0.0.0.0 www.box.anchorfree.net
0.0.0.0 rpt.anchorfree.net
0.0.0.0 www.rpt.anchorfree.net
0.0.0.0 123.box.anchorfree.net
0.0.0.0 www.123.box.anchorfree.net
0.0.0.0 anchorfree.us
0.0.0.0 www.anchorfree.us
0.0.0.0 delivery.anchorfree.us/land.php
0.0.0.0 www.delivery.anchorfree.us/land.php
0.0.0.0 rss2search.com
0.0.0.0 www.rss2search.com
0.0.0.0 mefeedia.com
0.0.0.0 www.mefeedia.com
0.0.0.0 a433.com
0.0.0.0 www.a433.com
0.0.0.0 techbrowsing.com
0.0.0.0 www.techbrowsing.com
0.0.0.0 techbrowsing.com/away.php
0.0.0.0 www.techbrowsing.com/away.php
0.0.0.0 update.mydati.com
0.0.0.0 www.update.mydati.com
0.0.0.0 mydati.com
0.0.0.0 www.mydati.com
0.0.0.0 geo.mydati.com 
0.0.0.0 www.geo.mydati.com 
0.0.0.0 updateeu.mydati.com
0.0.0.0 www.updateeu.mydati.com
0.0.0.0 east.mydati.com
0.0.0.0 www.east.mydati.com
0.0.0.0 west.mydati.com
0.0.0.0 www.west.mydati.com
0.0.0.0 us.mydati.com
0.0.0.0 www.us.mydati.com
0.0.0.0 eu.mydati.com
0.0.0.0 www.eu.mydati.com
0.0.0.0 myd3.mydati.com
0.0.0.0 www.myd3.mydati.com
0.0.0.0 ns2.mydati.com
0.0.0.0 www.ns2.mydati.com
0.0.0.0 ns1.mydati.com
0.0.0.0 www.ns1.mydati.com

jwtGenerator.js 文件

const jwt = require('jsonwebtoken');
require('dotenv').config(); 

function jwtGenerator(user_id) {
    const payload = {
        user: user_id
    }
    return jwt.sign(payload, process.env.jwtSecret, {expiresIn: "1h"})

}

module.exports = jwtGenerator; 

jwAuth.js 完整代码

const router = require('express').Router() 
const pool = require("../db")
const bcrypt = require("bcryptjs");
const jwtGenerator = require('../utils/jwtGenerator');
const authorization = require('../middleware/authorization');
// Registeration 

router.post("/register", async (req, res) => {
    try {

        // 1. Destructure the req.body (name, email, password) 

        const {name, email, password} = req.body; 

        // 2. Check if the user exists (If user already exists, then throw error)

        const user = await pool.query("SELECT * FROM users WHERE user_email = ", [email]);

        if (user.rows.length !== 0)
        {
            return res.status(401).send("User Already Exists");
        }

        // 3. Bcrypt the user password 

        const saltRound = 10; 
        const salt = await bcrypt.genSalt(saltRound); 
        const bcryptPassword = await bcrypt.hash(password, salt); 

        // 4. Enter the new user inside our database 

        const newUser = await pool.query("INSERT INTO users (user_name, user_email, user_password) values (, , ) RETURNING *", [name, email, bcryptPassword]);

        // 5. Generating Our JWT Token 

        const token = jwtGenerator(newUser.rows[0].user_id);

        res.json({token}); 

    } catch (err) {
        console.log(err.message); 
        res.status(500).send(`Server Error ${err}`); 
    }
})

// Login Route 

router.post("/login", async (req, res) => {
    try {

        // 1. Destructure the req.body 

        const {email, password} = req.body; 

        // 2. Check if user does not exist (Throw error if user does not exist)

        const user = await pool.query("Select * from users where user_email = ", [email]);

        if (user.rows.length === 0) {
            res.status(401).send("Email does not Exist"); 
        }

        // 3. Check if the password is same for the user in database 

        const validPassword = await bcrypt.compare(password, user.rows[0].user_password);
        if (!validPassword) {
            return res.status(401).send("Password is incorrect"); 
        }

        // 4. Give them a JWT Token 

        const token = jwtGenerator(user.rows[0].user_id); 

        res.json({token});


    } catch (err) {
        console.log(err.message); 
        res.status(500).send("Server Error")
    }
});

router.get("/is-verify", authorization, async (res, req) => {
    try {
        res.json(true); 
        
    } catch (err) {
         console.log(err.message); 
        res.status(500).send("Server Error")
    }
})

module.exports = router;

您忘记在您的身份验证中间件中调用 next,这将导致挂起请求。通过执行以下操作修复它:

module.exports = async (req, res, next) => {
    try {

        // ...       

        req.user = payload.user; 
        next();


    } catch (err) {
        console.log(err.message); 
        return res.status(403).json("You are not authorized");
    }
}