【问题标题】:How can I fix this error "RangeError [ERR_SOCKET_BAD_PORT]: Port should be >= 0 and < 65536. Received NaN."?如何修复此错误“RangeError [ERR_SOCKET_BAD_PORT]:端口应 >= 0 且 < 65536。收到 NaN。”?
【发布时间】:2021-12-25 03:37:11
【问题描述】:

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

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

recipe-cards.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”依赖导致问题或其他原因。我会继续测试和调试。

【问题讨论】:

  • 似乎是快速服务器设置中的一个问题,即未接收“8000”作为侦听端口。您能否展示您的快速服务器代码启动以及它如何设置端口 8000?
  • 请显示 poolConfig.js 中的代码
  • database/poolConfig.js 是做什么的?请向我们展示 node-postgres 的相关设置
  • @LuizFernandodaSilva 这是我的 server.js 文件,用于设置 express 后端 - codeshare.io/Qnk0Ex
  • @RobertKawecki 这是位于 poolConfig.js - codeshare.io/K8Z0x8 中的内容。它设置了我需要与 pool.query() 一起使用的数据(来自“pg”依赖项)以连接我的 Postgres 数据库。

标签: node.js reactjs postgresql express error-handling


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 2017-01-19
    • 2018-07-15
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多