如何修复此错误“RangeError [ERR_SOCKET_BAD_PORT]:端口应 >= 0 且 < 65536。收到 NaN。”?

gho*_*ost 1 postgresql error-handling node.js express reactjs

我最近在我的系统上下载了 Windows 11,从那时起(我不知道这是否是主要问题)我使用“npm start”启动我的react.js应用程序并在我的终端中激活nodemon,我得到一个“ RangeError [ERR_SOCKET_BAD_PORT] :端口应 >= 0 且 < 65536。收到 NaN “错误。

该应用程序本身可以在我的 localhost:3000 上使用,但在我的应用程序的一个部分中,我有以下代码从与 Postgres 数据库连接的节点 Express 服务器(通过使用 app.get())获取数据。

食谱卡.js

import React, { useState, useEffect } from 'react';

const RecipeSection = () => {

    const [data, setData] = useState([]);
 
    useEffect(() => {
        let interval;
        const fetchData = async () => {
            try {
                const url = "http://localhost:8000/recipes/display";
                const response = await fetch(url);
                const json = await response.json();

                setData(json);
                
            } catch(error) {
                console.error(error);
            }
    };

    fetchData();

    interval = setInterval(() => {
        fetchData()
      }, 86 * 1000)
      return () => {
        clearInterval(interval)
    }

    }, []); // Determine swhen to re-use useEffect, if this changes.

    return (
        <section className='recipe-card-grid'>
            {data.map(recipe => 
                (
                    <article key={recipe.recipe_id} className='recipe-card'>
                
                        <a href={recipe.video_url} rel='noopener noreferrer nofollow' target='_blank'>
                            <img src={recipe.img_path} alt={recipe.alt} className='recipe-card-image' />
                            <h2 className='center-text'>{recipe.recipe}</h2>
                        </a>
                        
                        <table>
                            <tbody>
                                <tr>
                                    <td>
                                        <img className='recipe-card-clock-icon' 
                                        src='/assets/ux/recipe-card-icons/clock.png' 
                                        alt='An icon that informs you about how long it might take to cook this recipe' />
                                    </td>
                                    <th>
                                        <p>&#8776;{recipe.cooking_time} min</p>
                                    </th> 
                                    <td>
                                        <img className='recipe-card-servings-icon' 
                                        src='/assets/ux/recipe-card-icons/servings.png' 
                                        alt='An icon that informs you about how many people can be served by following this recipe' />
                                    </td>
                                </tr>
                                <tr>
                                    <th>
                                        <p>x{recipe.servings} servings</p>
                                    </th>
                                </tr>
                            </tbody>
                        </table>
                            
                        <p className='center-text'>{recipe.summary}</p>

                    </article> 

                )
            )}
        </section>
    )
};

//RecipeSection
export default RecipeSection;
Run Code Online (Sandbox Code Playgroud)

与我尝试访问以获取数据库数据的路由相对应的代码。

const pool = require('../../database/poolConfig.js');

const displayRecipes = (req, res) => {
    
    const recipeFilter = 'SELECT * FROM recipes ORDER BY recipe_id ASC';
  
    pool.query(recipeFilter, (error, results) => {
      
      if(error) {
        console.error(error);

        res.status(403).json({
            success : false,
            msg : 'Could not display recipes.'
        })
      }

      const recipeJSON = results.rows; //!! results.rows[0]["recipe"]

      res.status(200).send(
          recipeJSON
        );
    })
}
Run Code Online (Sandbox Code Playgroud)

通常,此代码会使用与我在 Postgres 数据库中准备的烹饪食谱相对应的链接和图像填充我的网站,但现在它不执行任何操作,除了显示以下错误。

终端中的 Nodemon 错误

RangeError [ERR_SOCKET_BAD_PORT]: Port should be >= 0 and < 65536. Received NaN.
    at new NodeError (node:internal/errors:371:5)
    at validatePort (node:internal/validators:216:11)
    at lookupAndConnect (node:net:1013:5)
    at Socket.connect (node:net:989:5)
    at Connection.connect (C:\Users\hardg\Desktop\dj-bbq\node_modules\pg\lib\connection.js:38:17)
    at Client._connect (C:\Users\hardg\Desktop\dj-bbq\node_modules\pg\lib\client.js:113:11)
    at Client.connect (C:\Users\hardg\Desktop\dj-bbq\node_modules\pg\lib\client.js:161:12)
    at BoundPool.newClient (C:\Users\hardg\Desktop\dj-bbq\node_modules\pg-pool\index.js:229:12)
    at BoundPool.connect (C:\Users\hardg\Desktop\dj-bbq\node_modules\pg-pool\index.js:204:10)
    at BoundPool.query (C:\Users\hardg\Desktop\dj-bbq\node_modules\pg-pool\index.js:361:10)
Run Code Online (Sandbox Code Playgroud)

我不知道如何解决这个问题。有人有一些想法或者我应该提供更多信息吗?

package.json内容

{
  "name": "not-set",
  "version": "0.0.0",
  "description": "--",
  "author": "not-set",
  "private": true,
  "engines": {
    "node": "11.x"
  },
  "dependencies": {
    "@formspree/react": "^2.2.4",
    "@stripe/react-stripe-js": "^1.5.0",
    "@stripe/stripe-js": "^1.19.0",
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "cors": "^2.8.5",
    "dotenv": "^10.0.0",
    "express": "^4.17.1",
    "helmet": "^4.6.0",
    "pg": "^8.7.1",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-router-dom": "^5.3.0",
    "react-scripts": "4.0.3",
    "stripe": "^8.184.0",
    "web-vitals": "^1.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "server": "node app-server/server.js",
    "nodemon": "nodemon app-server/server.js"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "nodemon": "^2.0.15"
  }
}
Run Code Online (Sandbox Code Playgroud)

更新:

我做了一个常规的 app.get() 路线...

router.get('/test', (req, res) => {
        res.status(200).send('The Basic API endpoints are working.')
    });
Run Code Online (Sandbox Code Playgroud)

...在一个终端中编写 npm start 并启动 nodemon 后,我用 Postman 对其进行了测试。结果是 Postman 能够到达 API 端点并返回“基本 API 端点正在工作”。

这意味着正在设置端口并且可以访问 API 端点。因此问题必须出在recipe-cards.js 文件上(可能)。“node-Postgres”又名“pg”依赖项导致了问题或其他原因。我会继续测试和调试。

gho*_*ost 5

我能够修复它。问题出在我的 .env 文件和“dotenv”依赖项上。简而言之,该错误不是在谈论 Express 服务器“端口”,而是在谈论“pg”依赖项想要用来访问我通过使用“pool”在自己的本地计算机上设置的数据库的 Postgres 数据库“端口”。 query()' 以及我在与数据库对应的 .env 文件中设置的信息:用户、数据库名称、端口、密码等。环境变量之一,在我的例子中,“端口”已更改,因此我必须将 .env 文件更改为新文件。
我希望这是有道理的。