Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/442.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Heroku-web.1:在node.js应用程序中崩溃_Javascript_Node.js_Express_Heroku - Fatal编程技术网

Javascript Heroku-web.1:在node.js应用程序中崩溃

Javascript Heroku-web.1:在node.js应用程序中崩溃,javascript,node.js,express,heroku,Javascript,Node.js,Express,Heroku,所以我第一次尝试在heroku中部署node.js应用程序 在部署我的代码并进入heroku部署指南中的第6步后: 它告诉我它部署得很好,所以我打开了“应用程序错误”——浏览器控制台是503 接下来,我向我的项目添加了一个Procfile,重新部署,然后运行heroku pstop,返回以下内容: === web (Free): yarn start:production (1) web.1: crashed 2018/01/30 13:17:05 +0000 (~ 5m ago) 我不太确定

所以我第一次尝试在heroku中部署node.js应用程序

在部署我的代码并进入heroku部署指南中的第6步后:

它告诉我它部署得很好,所以我打开了“应用程序错误”——浏览器控制台是
503

接下来,我向我的项目添加了一个Procfile,重新部署,然后运行
heroku ps
top,返回以下内容:

=== web (Free): yarn start:production (1)
web.1: crashed 2018/01/30 13:17:05 +0000 (~ 5m ago)
我不太确定接下来该怎么办,因为heroku指南没有解释如果我遇到这个错误该怎么办

以下是my node.js应用程序的最初几页:

package.json

{
  "name": "",
  "version": "2.5.1",
  "description": "",
  "main": "index.js",
  "engines": {
    "node": ">=6.0",
    "npm": ">=3.0"
  },
  "repository": {
    "type": "git",
    "url": ""
  }
  "author": "",
  "license": "",
  "bugs": {
    "url": ""
  },
  "homepage": "",
  "scripts": {
    "start": "better-npm-run start",
    "start:production": "yarn build && yarn start:prod",
    "start:prod": "better-npm-run start:prod",
    "build": "yarn clean:build && better-npm-run build",
    "lint": "yarn lint:js && yarn lint:style",
    "lint:js": "better-npm-run lint:js",
    "lint:style": "better-npm-run lint:style",
    "flow": "better-npm-run flow",
    "test": "better-npm-run test",
    "test:watch": "yarn test --watch",
    "clean:all": "yarn clean:build && yarn clean:test",
    "clean:build": "better-npm-run clean:build",
    "clean:test": "better-npm-run clean:test",
    "coveralls": "better-npm-run coveralls && yarn clean:test"
  },
  "betterScripts": {
    "start": {
      "command": "nodemon ./index.js",
      "env": {
        "NODE_PATH": "./src",
        "NODE_ENV": "development",
        "PORT": 3000
      }
    },
    "start:prod": {
      "command": "node ./index.js",
      "env": {
        "NODE_PATH": "./src",
        "NODE_ENV": "production",
        "PORT": 8080
      }
    },
    "build": {
      "command": "webpack --progress --hide-modules --config ./tools/webpack/config.babel.js",
      "env": {
        "NODE_ENV": "production"
      }
    },
    "lint:js": {
      "command": "eslint ./src ./tools ./index.js"
    },
    "lint:style": {
      "command": "stylelint \"./src/**/*.scss\" --syntax scss"
    },
    "flow": {
      "command": "flow; test $? -eq 0 -o $? -eq 2"
    },
    "test": {
      "command": "jest --coverage",
      "env": {
        "NODE_ENV": "test"
      }
    },
    "clean:build": {
      "command": "rimraf ./public/assets"
    },
    "clean:test": {
      "command": "rimraf ./coverage"
    },
    "coveralls": {
      "command": "cat ./coverage/lcov.info | coveralls"
    }
  },
  "babel": {
    "presets": [
      "env",
      "react",
      "stage-0"
    ],
    "env": {
      "production": {
        "plugins": [
          "transform-remove-console"
        ]
      }
    }
  },
  "eslintConfig": {
    "parser": "babel-eslint",
    "extends": "airbnb",
    "plugins": [
      "react",
      "jsx-a11y",
      "import"
    ],
    "env": {
      "browser": true,
      "node": true,
      "jest": true,
      "es6": true
    },
    "rules": {
      "linebreak-style": 0,
      "global-require": 0,
      "no-underscore-dangle": 0,
      "no-console": 0,
      "react/jsx-filename-extension": [
        1,
        {
          "extensions": [
            ".js",
            ".jsx"
          ]
        }
      ],
      "import/no-extraneous-dependencies": [
        "error",
        {
          "devDependencies": true
        }
      ],
      "function-paren-newline": 0
    },
    "globals": {
      "__CLIENT__": true,
      "__SERVER__": true,
      "__DISABLE_SSR__": true,
      "__DEV__": true,
      "webpackIsomorphicTools": true
    }
  },
  "stylelint": {
    "extends": "stylelint-config-standard",
    "rules": {
      "string-quotes": "single",
      "selector-pseudo-class-no-unknown": [
        true,
        {
          "ignorePseudoClasses": [
            "global",
            "local"
          ]
        }
      ]
    }
  },
  "browserslist": [
    "last 2 versions",
    "not ie <= 8"
  ],
  "jest": {
    "setupFiles": [
      "raf/polyfill",
      "<rootDir>/tools/jest/setup.js"
    ],
    "collectCoverageFrom": [
      "src/containers/**/*.js",
      "src/components/**/*.js",
      "!src/**/__tests__"
    ],
    "moduleNameMapper": {
      ".*\\.(css|scss|sass)$": "<rootDir>/tools/jest/styleMock.js",
      ".*\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/tools/jest/assetMock.js"
    }
  }
}
WIT.config.js

/* @flow */

// Use babel-register to precompile ES6 syntax
require('babel-core/register');

const WebpackIsomorphicTools = require('webpack-isomorphic-tools');

// Setup global variables for server
global.__CLIENT__ = false;
global.__SERVER__ = true;
global.__DISABLE_SSR__ = false; // Disable server side render here
global.__DEV__ = process.env.NODE_ENV !== 'production';

// This should be the same with webpack context
const dirRoot = require('path').join(process.cwd());

// Settings of webpack-isomorphic-tools
global.webpackIsomorphicTools =
  new WebpackIsomorphicTools(require('./tools/webpack/WIT.config')).server(dirRoot, () => require('./src/server'));
const WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin');

module.exports = {
  // debug: true,
  // webpack_assets_file_path: 'webpack-assets.json',
  // webpack_stats_file_path: 'webpack-stats.json',
  assets: {
    images: {
      extensions: ['png', 'jpg', 'jpeg', 'gif'],
      parser: WebpackIsomorphicToolsPlugin.url_loader_parser,
    },
    fonts: {
      extensions: ['eot', 'ttf', 'woff', 'woff2'],
      parser: WebpackIsomorphicToolsPlugin.url_loader_parser,
    },
    svg: {
      extension: 'svg',
      parser: WebpackIsomorphicToolsPlugin.url_loader_parser,
    },
    style_modules: {
      extensions: ['css', 'scss'],
      filter: (module, regex, options, log) => {
        if (options.development) {
          return WebpackIsomorphicToolsPlugin.style_loader_filter(module, regex, options, log);
        }

        return regex.test(module.name);
      },
      path: (module, options, log) => {
        if (options.development) {
          return WebpackIsomorphicToolsPlugin.style_loader_path_extractor(module, options, log);
        }

        return module.name;
      },
      parser: (module, options, log) => {
        if (options.development) {
          return WebpackIsomorphicToolsPlugin.css_modules_loader_parser(module, options, log);
        }

        return module.source;
      },
    },
  },
};
   /* @flow */

import path from 'path';
import morgan from 'morgan';
import express from 'express';
import compression from 'compression';
import helmet from 'helmet';
import hpp from 'hpp';
import favicon from 'serve-favicon';
import React from 'react';
import { renderToString, renderToStaticMarkup } from 'react-dom/server';
import { StaticRouter, matchPath } from 'react-router-dom';
import { Provider } from 'react-redux';
import chalk from 'chalk';

import createHistory from 'history/createMemoryHistory';
import configureStore from './redux/store';
import Html from './utils/Html';
import App from './containers/App';
import routes from './routes';
import { port, host } from './config';

const app = express();

app.set('port', process.env.PORT || 3000);

// Using helmet to secure Express with various HTTP headers
app.use(helmet());
// Prevent HTTP parameter pollution.
app.use(hpp());
// Compress all requests
app.use(compression());

// Use morgan for http request debug (only show error)
app.use(morgan('dev', { skip: (req, res) => res.statusCode < 400 }));
app.use(favicon(path.join(process.cwd(), './public/favicon.ico')));
app.use(express.static(path.join(process.cwd(), './public')));

// Run express as webpack dev server
if (__DEV__) {
  const webpack = require('webpack');
  const webpackConfig = require('../tools/webpack/config.babel');

  const compiler = webpack(webpackConfig);

  app.use(require('webpack-dev-middleware')(compiler, {
    publicPath: webpackConfig.output.publicPath,
    hot: true,
    noInfo: true,
    stats: { colors: true },
    serverSideRender: true,
  }));

  app.use(require('webpack-hot-middleware')(compiler));
}

//GET week
app.get('/api/week', (req, res) => {
    console.log('week');

    var articles = [];

    db.collection('articles')
        .find()
        .limit(2)
        .sort("date", -1)
        .toArray()
        .then(result => {
            articles = articles.concat(result);
        }).then(() => {
            // console.log(articles);
            res.send(articles);
        }).catch(e => {
            console.error(e);
        });

});

//GET articles
app.get('/api/articles', (req, res) => {
    console.log('articles');

    var articles = [];

    db.collection('articles')
        .find()
        .limit(12)
        .sort("date", -1)
        .toArray()
        .then(result => {
            articles = articles.concat(result);
        }).then(() => {
            // console.log(articles);
            res.send(articles);
        }).catch(e => {
            console.error(e);
        });

});

//GET authorArticles
app.get('/api/authorArticles', (req, res) => {
    console.log('authorArticles');

    var articles = [];

    var ObjectId = require('mongodb').ObjectID;
    var author = {};
    var param = req.query.authorQuery;
    param = param.replace(/-/g, ' ');

    db.collection('articles')
        // .find()
        .find({"author" : {$regex : ".*" + param + ".*"}})
        .limit(12)
        .sort("date", -1)
        .toArray()
        .then(result => {
            articles = articles.concat(result);
        }).then(() => {
            // console.log(articles);
            res.send(articles);
        }).catch(e => {
            console.error(e);
        });

});

//GET extra
app.get('/api/extra', (req, res) => {
    console.log('extra');

    var articles = [];

    db.collection('articles')
        .aggregate([{ $sample: { size: 4 } }])
        .toArray()
        .then(result => {
            articles = articles.concat(result);
        }).then(() => {
            // console.log(articles);
            res.send(articles);
        }).catch(e => {
            console.error(e);
        });

});

//GET authors
app.get('/api/authors', (req, res) => {
    console.log('authors');

    var authors = [];

    db.collection('authors')
        .find()
        .limit(24)
        .toArray()
        .then(result => {
            // console.log(result);
            authors = authors.concat(result);
        }).then(() => {
            res.send(authors);
        }).catch(e => {
            console.error(e);
        });

});

//GET search
app.get('/api/search', (req, res) => {
    console.log('/api/search');

    var articles = [];

    db.collection('articles')
        .find({$or:[
                {title: {$regex : ".*" + req.query.searchQuery + ".*"}},
                {description: {$regex : ".*" + req.query.searchQuery + ".*"}},
                {author: {$regex : ".*" + req.query.searchQuery + ".*"}},
                {keywords: {$regex : ".*" + req.query.searchQuery + ".*"}}
              ]})
        .limit(24)
        .sort("date", -1)
        .toArray()
        .then(result => {
            articles = articles.concat(result);
        }).then(() => {
            // console.log(articles);
            res.send(articles);
        }).catch(e => {
            console.error(e);
        });

});

//GET category
app.get('/api/category', (req, res) => {
    console.log('category');

    var articles = [];

    db.collection('articles')
        .find({$or:[
                {category: {$regex : ".*" + req.query.categoryQuery + ".*"}}
              ]})
        .limit(12)
        .sort("date", -1)
        .toArray()
        .then(result => {
            articles = articles.concat(result);
        }).then(() => {
            // console.log(articles);
            res.send(articles);
        }).catch(e => {
            console.error(e);
        });

});

//GET article
app.get('/api/article', (req, res) => {
    console.log('article');

    var ObjectId = require('mongodb').ObjectID;
    var article = {};
    var param = req.query.title;
    param = param.replace(/-/g, ' ');

    db.collection('articles')
        .findOne({"title": param})
        .then(result => {
            article = result;
        }).then(() => {
            res.send(article);
        }).catch(e => {
            console.error(e);
        });

});

//GET author
app.get('/api/author', (req, res) => {
    console.log('author');

    var ObjectId = require('mongodb').ObjectID;
    var article = {};
    var param = req.query.title;
    param = param.replace(/-/g, ' ');

    db.collection('authors')
        .findOne({"name": param})
        .then(result => {
            article = result;
        }).then(() => {
            res.send(article);
        }).catch(e => {
            console.error(e);
        });

});

// Register server-side rendering middleware
app.get('*', (req, res) => {
  if (__DEV__) webpackIsomorphicTools.refresh();

  const history = createHistory();
  const store = configureStore(history);
  const renderHtml = (store, htmlContent) => { // eslint-disable-line no-shadow
    const html = renderToStaticMarkup(<Html store={store} htmlContent={htmlContent} />);

    return `<!doctype html>${html}`;
  };

  // If __DISABLE_SSR__ = true, disable server side rendering
  if (__DISABLE_SSR__) {
    res.send(renderHtml(store));
    return;
  }

  // Load data on server-side
  const loadBranchData = () => {
    const promises = [];

    routes.some((route) => {
      const match = matchPath(req.path, route);

      // $FlowFixMe: the params of pre-load actions are dynamic
      if (match && route.loadData) promises.push(route.loadData(store.dispatch, match.params));

      return match;
    });

    return Promise.all(promises);
  };

  // Send response after all the action(s) are dispathed
  loadBranchData()
    .then(() => {
      // Setup React-Router server-side rendering
      const routerContext = {};
      const htmlContent = renderToString(
        <Provider store={store}>
          <StaticRouter location={req.url} context={routerContext}>
            <App />
          </StaticRouter>
        </Provider>,
      );

      // Check if the render result contains a redirect, if so we need to set
      // the specific status and redirect header and end the response
      if (routerContext.url) {
        res.status(301).setHeader('Location', routerContext.url);
        res.end();

        return;
      }

      // Checking is page is 404
      const status = routerContext.status === '404' ? 404 : 200;

      // Pass the route and initial state into html template
      res.status(status).send(renderHtml(store, htmlContent));
    })
    .catch((err) => {
      res.status(404).send('Not Found :(');

      console.error(`==> You seem to be setting the PORT env var in your package.json. You should not be doing that for Heroku. Heroku sets if for you automatically.
Instead, add something like this in your server.js:

    app.set('port', process.env.PORT || 3000);
server.js

/* @flow */

// Use babel-register to precompile ES6 syntax
require('babel-core/register');

const WebpackIsomorphicTools = require('webpack-isomorphic-tools');

// Setup global variables for server
global.__CLIENT__ = false;
global.__SERVER__ = true;
global.__DISABLE_SSR__ = false; // Disable server side render here
global.__DEV__ = process.env.NODE_ENV !== 'production';

// This should be the same with webpack context
const dirRoot = require('path').join(process.cwd());

// Settings of webpack-isomorphic-tools
global.webpackIsomorphicTools =
  new WebpackIsomorphicTools(require('./tools/webpack/WIT.config')).server(dirRoot, () => require('./src/server'));
const WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin');

module.exports = {
  // debug: true,
  // webpack_assets_file_path: 'webpack-assets.json',
  // webpack_stats_file_path: 'webpack-stats.json',
  assets: {
    images: {
      extensions: ['png', 'jpg', 'jpeg', 'gif'],
      parser: WebpackIsomorphicToolsPlugin.url_loader_parser,
    },
    fonts: {
      extensions: ['eot', 'ttf', 'woff', 'woff2'],
      parser: WebpackIsomorphicToolsPlugin.url_loader_parser,
    },
    svg: {
      extension: 'svg',
      parser: WebpackIsomorphicToolsPlugin.url_loader_parser,
    },
    style_modules: {
      extensions: ['css', 'scss'],
      filter: (module, regex, options, log) => {
        if (options.development) {
          return WebpackIsomorphicToolsPlugin.style_loader_filter(module, regex, options, log);
        }

        return regex.test(module.name);
      },
      path: (module, options, log) => {
        if (options.development) {
          return WebpackIsomorphicToolsPlugin.style_loader_path_extractor(module, options, log);
        }

        return module.name;
      },
      parser: (module, options, log) => {
        if (options.development) {
          return WebpackIsomorphicToolsPlugin.css_modules_loader_parser(module, options, log);
        }

        return module.source;
      },
    },
  },
};
   /* @flow */

import path from 'path';
import morgan from 'morgan';
import express from 'express';
import compression from 'compression';
import helmet from 'helmet';
import hpp from 'hpp';
import favicon from 'serve-favicon';
import React from 'react';
import { renderToString, renderToStaticMarkup } from 'react-dom/server';
import { StaticRouter, matchPath } from 'react-router-dom';
import { Provider } from 'react-redux';
import chalk from 'chalk';

import createHistory from 'history/createMemoryHistory';
import configureStore from './redux/store';
import Html from './utils/Html';
import App from './containers/App';
import routes from './routes';
import { port, host } from './config';

const app = express();

app.set('port', process.env.PORT || 3000);

// Using helmet to secure Express with various HTTP headers
app.use(helmet());
// Prevent HTTP parameter pollution.
app.use(hpp());
// Compress all requests
app.use(compression());

// Use morgan for http request debug (only show error)
app.use(morgan('dev', { skip: (req, res) => res.statusCode < 400 }));
app.use(favicon(path.join(process.cwd(), './public/favicon.ico')));
app.use(express.static(path.join(process.cwd(), './public')));

// Run express as webpack dev server
if (__DEV__) {
  const webpack = require('webpack');
  const webpackConfig = require('../tools/webpack/config.babel');

  const compiler = webpack(webpackConfig);

  app.use(require('webpack-dev-middleware')(compiler, {
    publicPath: webpackConfig.output.publicPath,
    hot: true,
    noInfo: true,
    stats: { colors: true },
    serverSideRender: true,
  }));

  app.use(require('webpack-hot-middleware')(compiler));
}

//GET week
app.get('/api/week', (req, res) => {
    console.log('week');

    var articles = [];

    db.collection('articles')
        .find()
        .limit(2)
        .sort("date", -1)
        .toArray()
        .then(result => {
            articles = articles.concat(result);
        }).then(() => {
            // console.log(articles);
            res.send(articles);
        }).catch(e => {
            console.error(e);
        });

});

//GET articles
app.get('/api/articles', (req, res) => {
    console.log('articles');

    var articles = [];

    db.collection('articles')
        .find()
        .limit(12)
        .sort("date", -1)
        .toArray()
        .then(result => {
            articles = articles.concat(result);
        }).then(() => {
            // console.log(articles);
            res.send(articles);
        }).catch(e => {
            console.error(e);
        });

});

//GET authorArticles
app.get('/api/authorArticles', (req, res) => {
    console.log('authorArticles');

    var articles = [];

    var ObjectId = require('mongodb').ObjectID;
    var author = {};
    var param = req.query.authorQuery;
    param = param.replace(/-/g, ' ');

    db.collection('articles')
        // .find()
        .find({"author" : {$regex : ".*" + param + ".*"}})
        .limit(12)
        .sort("date", -1)
        .toArray()
        .then(result => {
            articles = articles.concat(result);
        }).then(() => {
            // console.log(articles);
            res.send(articles);
        }).catch(e => {
            console.error(e);
        });

});

//GET extra
app.get('/api/extra', (req, res) => {
    console.log('extra');

    var articles = [];

    db.collection('articles')
        .aggregate([{ $sample: { size: 4 } }])
        .toArray()
        .then(result => {
            articles = articles.concat(result);
        }).then(() => {
            // console.log(articles);
            res.send(articles);
        }).catch(e => {
            console.error(e);
        });

});

//GET authors
app.get('/api/authors', (req, res) => {
    console.log('authors');

    var authors = [];

    db.collection('authors')
        .find()
        .limit(24)
        .toArray()
        .then(result => {
            // console.log(result);
            authors = authors.concat(result);
        }).then(() => {
            res.send(authors);
        }).catch(e => {
            console.error(e);
        });

});

//GET search
app.get('/api/search', (req, res) => {
    console.log('/api/search');

    var articles = [];

    db.collection('articles')
        .find({$or:[
                {title: {$regex : ".*" + req.query.searchQuery + ".*"}},
                {description: {$regex : ".*" + req.query.searchQuery + ".*"}},
                {author: {$regex : ".*" + req.query.searchQuery + ".*"}},
                {keywords: {$regex : ".*" + req.query.searchQuery + ".*"}}
              ]})
        .limit(24)
        .sort("date", -1)
        .toArray()
        .then(result => {
            articles = articles.concat(result);
        }).then(() => {
            // console.log(articles);
            res.send(articles);
        }).catch(e => {
            console.error(e);
        });

});

//GET category
app.get('/api/category', (req, res) => {
    console.log('category');

    var articles = [];

    db.collection('articles')
        .find({$or:[
                {category: {$regex : ".*" + req.query.categoryQuery + ".*"}}
              ]})
        .limit(12)
        .sort("date", -1)
        .toArray()
        .then(result => {
            articles = articles.concat(result);
        }).then(() => {
            // console.log(articles);
            res.send(articles);
        }).catch(e => {
            console.error(e);
        });

});

//GET article
app.get('/api/article', (req, res) => {
    console.log('article');

    var ObjectId = require('mongodb').ObjectID;
    var article = {};
    var param = req.query.title;
    param = param.replace(/-/g, ' ');

    db.collection('articles')
        .findOne({"title": param})
        .then(result => {
            article = result;
        }).then(() => {
            res.send(article);
        }).catch(e => {
            console.error(e);
        });

});

//GET author
app.get('/api/author', (req, res) => {
    console.log('author');

    var ObjectId = require('mongodb').ObjectID;
    var article = {};
    var param = req.query.title;
    param = param.replace(/-/g, ' ');

    db.collection('authors')
        .findOne({"name": param})
        .then(result => {
            article = result;
        }).then(() => {
            res.send(article);
        }).catch(e => {
            console.error(e);
        });

});

// Register server-side rendering middleware
app.get('*', (req, res) => {
  if (__DEV__) webpackIsomorphicTools.refresh();

  const history = createHistory();
  const store = configureStore(history);
  const renderHtml = (store, htmlContent) => { // eslint-disable-line no-shadow
    const html = renderToStaticMarkup(<Html store={store} htmlContent={htmlContent} />);

    return `<!doctype html>${html}`;
  };

  // If __DISABLE_SSR__ = true, disable server side rendering
  if (__DISABLE_SSR__) {
    res.send(renderHtml(store));
    return;
  }

  // Load data on server-side
  const loadBranchData = () => {
    const promises = [];

    routes.some((route) => {
      const match = matchPath(req.path, route);

      // $FlowFixMe: the params of pre-load actions are dynamic
      if (match && route.loadData) promises.push(route.loadData(store.dispatch, match.params));

      return match;
    });

    return Promise.all(promises);
  };

  // Send response after all the action(s) are dispathed
  loadBranchData()
    .then(() => {
      // Setup React-Router server-side rendering
      const routerContext = {};
      const htmlContent = renderToString(
        <Provider store={store}>
          <StaticRouter location={req.url} context={routerContext}>
            <App />
          </StaticRouter>
        </Provider>,
      );

      // Check if the render result contains a redirect, if so we need to set
      // the specific status and redirect header and end the response
      if (routerContext.url) {
        res.status(301).setHeader('Location', routerContext.url);
        res.end();

        return;
      }

      // Checking is page is 404
      const status = routerContext.status === '404' ? 404 : 200;

      // Pass the route and initial state into html template
      res.status(status).send(renderHtml(store, htmlContent));
    })
    .catch((err) => {
      res.status(404).send('Not Found :(');

      console.error(`==> You seem to be setting the PORT env var in your package.json. You should not be doing that for Heroku. Heroku sets if for you automatically.
Instead, add something like this in your server.js:

    app.set('port', process.env.PORT || 3000);
/*@flow*/
从“路径”导入路径;
从“摩根”进口摩根;
从“快递”进口快递;
从“压缩”导入压缩;
从“头盔”导入头盔;
从“水电站”进口水电站;
从“服务favicon”进口favicon;
从“React”导入React;
从'react dom/server'导入{renderToString,renderToStaticMarkup};
从“react router dom”导入{StaticRouter,matchPath};
从'react redux'导入{Provider};
从“粉笔”导入粉笔;
从“历史记录/createMemoryHistory”导入createHistory;
从“/redux/store”导入配置存储;
从“/utils/Html”导入Html;
从“./containers/App”导入应用程序;
从“./routes”导入路由;
从“/config”导入{port,host};
常量app=express();
应用程序集('port',process.env.port | | 3000);
//使用头盔保护带有各种HTTP头的Express
应用(头盔());
//防止HTTP参数污染。
应用程序使用(hpp());
//压缩所有请求
app.use(compression());
//使用morgan进行http请求调试(仅显示错误)
应用程序使用(morgan('dev',{skip:'req,res)=>res.statusCode<400});
使用(favicon(path.join(process.cwd(),'./public/favicon.ico'));
app.use(express.static(path.join(process.cwd(),'./public'));
//以Web包开发服务器的身份运行express
如果(开发){
const webpack=require('webpack');
const webpackConfig=require('../tools/webpack/config.babel');
const compiler=webpack(webpackConfig);
app.use(需要('webpack-dev-middleware')(编译器{
publicPath:webpackConfig.output.publicPath,
热:是的,
没错,
统计信息:{colors:true},
serverSideRender:true,
}));
app.use(需要('webpack-hot-middleware')(编译器));
}
//得到一周
app.get('/api/week',(req,res)=>{
console.log(“周”);
var条款=[];
db.集合(“文章”)
.find()
.限额(2)
.sort(“日期”,-1)
.toArray()
。然后(结果=>{
articles=articles.concat(结果);
}).然后(()=>{
//控制台日志(文章);
res.send(文章);
}).catch(e=>{
控制台错误(e);
});
});
//获取文章
app.get('/api/articles',(req,res)=>{
console.log(“文章”);
var条款=[];
db.集合(“文章”)
.find()
.限额(12)
.sort(“日期”,-1)
.toArray()
。然后(结果=>{
articles=articles.concat(结果);
}).然后(()=>{
//控制台日志(文章);
res.send(文章);
}).catch(e=>{
控制台错误(e);
});
});
//获取作者文章
app.get('/api/authorArticles',(req,res)=>{
log('authorArticles');
var条款=[];
var ObjectId=require('mongodb')。ObjectId;
var author={};
var param=req.query.authorQuery;
参数=参数替换(/-/g');
db.集合(“文章”)
//.find()
.find({“author”:{$regex:'%1!'+param+“*”}})
.限额(12)
.sort(“日期”,-1)
.toArray()
。然后(结果=>{
articles=articles.concat(结果);
}).然后(()=>{
//控制台日志(文章);
res.send(文章);
}).catch(e=>{
控制台错误(e);
});
});
//额外获得
app.get('/api/extra',(req,res)=>{
console.log('extra');
var条款=[];
db.集合(“文章”)
.aggregate([{$sample:{size:4}}}])
.toArray()
。然后(结果=>{
articles=articles.concat(结果);
}).然后(()=>{
//控制台日志(文章);
res.send(文章);
}).catch(e=>{
控制台错误(e);
});
});
//获取作者
app.get('/api/authors',(req,res)=>{
console.log('authors');
var=[];
db.collection('作者')
.find()
.限额(24)
.toArray()
。然后(结果=>{
//控制台日志(结果);
authors=authors.concat(结果);
}).然后(()=>{
res.send(作者);
}).catch(e=>{
控制台错误(e);
});
});
//搜索
app.get('/api/search',(req,res)=>{
log('/api/search');
var条款=[];
db.集合(“文章”)
.查找({$or):[
{title:{$regex:'%1!'+req.query.searchQuery+“*”},
{description:{$regex:'%1!'+req.query.searchQuery+“*”},
{作者:{$regex:“.*+req.query.searchQuery+”*“},
{关键字:{$regex:'%1!'+req.query.searchQuery+“*”}
]})
.限额(24)
.sort(“日期”,-1)
.toArray()
。然后(结果=>{
articles=articles.concat(结果);
}).然后(()=>{
//控制台日志(文章);
res.send(文章);
}).catch(e=>{
控制台错误(e);
});
});
//获取类别
app.get('/api/category',(req,res)=>{
console.log('category');
var条款=[];
db.集合(“文章”)
.查找({$or):[
{category:{$regex:'%1!'+req.query.categoryQuery+“*”}
]})
.限额(12)
.sort(“日期”,-1)
.toArray()
。然后(结果=>{
A.