如何修复此错误“RangeError [ERR_SOCKET_BAD_PORT]:端口应 >= 0 且 < 65536. Received NaN."?

问题描述 投票:0回答:2

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

应用程序本身可以在我的 localhost:3000 上使用,但在我的应用程序的一个部分中,我有以下代码从连接 Postgres 数据库的 Node 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;

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

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
        );
    })
}

通常,此代码会使用与我在 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)

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

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"
  }
}

更新:

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

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

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

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

node.js reactjs postgresql express error-handling
2个回答
5
投票

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


0
投票

我有相同的错误类型,并一直在尝试解决它。我本地计算机中的 PSQL 与 github 中的 .env 具有相同的池化值。然而问题依然存在。

有人能帮我解决这个问题吗?

检查我的 github 存储库:https://github.com/BiruSkai/simple-e-commerce/blob/main/server/config/index.js.

以下是运行nodemon app.js后的错误信息:

节点:内部/验证器:424 抛出新的ERR_SOCKET_BAD_PORT(名称,端口,allowZero); ^

RangeError [ERR_SOCKET_BAD_PORT]:options.port 应该 >= 0 且 < 65536. Received type number (NaN). at validatePort (node:internal/validators:424:11) at Server.listen (node:net:2000:5) at Function.listen (D:\project coding 1.1.2024\FullStack\simple-e-commerce\server\node_modules\express\lib\application.js:635:24) at Object. (D:\project coding 1.1.2024\FullStack\simple-e-commerce\server\app.js:30:5) at Module._compile (node:internal/modules/cjs/loader:1376:14) at Module._extensions..js (node:internal/modules/cjs/loader:1435:10) at Module.load (node:internal/modules/cjs/loader:1207:32) at Module._load (node:internal/modules/cjs/loader:1023:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:135:12) at node:internal/main/run_main_module:28:49 { code: 'ERR_SOCKET_BAD_PORT'

© www.soinside.com 2019 - 2024. All rights reserved.