首页 > 解决方案 > 使用listen()方法在node.js中设置端口

问题描述

我正在尝试将我的第一个 node.js 部署到 Heroku,但我不断收到 H10-App 崩溃错误。

我已经做了一些谷歌搜索,我很确定我在不知不觉中设置了端口,即使看不到我在代码中的位置。我尝试使用 listen() 动态设置端口,但仍然收到 h10 错误。

这是我的 index.js 文件

import { createTable, tableData, createButton } from './ladderFuncs';
import thisYear from './yearFunc';

const container = document.createElement('div');
container.setAttribute('class', 'container');
document.body.appendChild(container);

const request = new XMLHttpRequest();
request.open('GET', 'https://api.squiggle.com.au/?q=standings', true);

request.onload = function apiData() {
  const data = JSON.parse(this.response).standings;

  if (request.status >= 200 && request.status < 400) {
    const title = document.createElement('h1');
    container.appendChild(title);
    title.innerHTML = `${thisYear()} AFL Premiership Season`;
    createButton();
    createTable();
    tableData(data);
  } else {
    const errorMessage = document.createElement('div');
    errorMessage.textContent = 'Out of bounds! On the full!';
    container.appendChild(errorMessage);
  }
};

const server = require('http');

server.listen(process.env.PORT || 5000);

request.send();

这是我的 package.json

  "name": "aflapi",
  "version": "1.0.0",
  "description": "Using the AFL API from Squiggle to create a simple AFL ladder App",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server --mode development",
    "build": "webpack --config ./webpack.config.js --mode production",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/benfanderson/aflApp.git"
  },
  "author": "Ben Anderson",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.7.7",
    "@babel/plugin-proposal-object-rest-spread": "^7.7.7",
    "@babel/preset-env": "^7.7.7",
    "babel-eslint": "^10.0.3",
    "babel-loader": "^8.0.6",
    "clean-webpack-plugin": "^3.0.0",
    "css-loader": "^3.4.1",
    "eslint": "^6.1.0",
    "eslint-config-airbnb": "^18.0.1",
    "eslint-loader": "^3.0.3",
    "eslint-plugin-import": "^2.19.1",
    "eslint-plugin-jsx-a11y": "^6.2.3",
    "eslint-plugin-react": "^7.17.0",
    "eslint-plugin-react-hooks": "^1.7.0",
    "fibers": "^4.0.2",
    "file-loader": "^5.0.2",
    "html-webpack-plugin": "^3.2.0",
    "node-sass": "^4.13.1",
    "sass": "^1.24.4",
    "sass-loader": "^8.0.0",
    "style-loader": "^1.1.2",
    "url-loader": "^3.0.0",
    "webpack": "^4.41.5",
    "webpack-cli": "^3.3.10",
    "webpack-dev-server": "^3.10.1"
  },
  "babel": {
    "presets": [
      "@babel/preset-env"
    ],
    "plugins": [
      "@babel/plugin-proposal-object-rest-spread"
    ]
  }
}

我是否需要将整个内容包装在 http.createServer() 方法中?

任何帮助将不胜感激。

标签: javascriptnode.jsherokuport

解决方案


您可以像这样创建服务器

const http = require('http');
const server = http.createServer((req,res)=>{
//handle requests
});

server.listen(process.env.PORT || 5000);

request.send();

希望这可以帮助

只需确保您可以在本地运行代码而不会出错,然后再部署到 heroku


推荐阅读