【问题标题】:FetchError: request to http://localhost:3000/api/projects failed, reason: connect ECONNREFUSED 127.0.0.1:3000 (Express/Next.Js)FetchError:对 http://localhost:3000/api/projects 的请求失败,原因:连接 ECONNREFUSED 127.0.0.1:3000 (Express/Next.Js)
【发布时间】:2019-08-09 12:54:59
【问题描述】:

我有一个 API 路由,当项目页面(组件)被加载时,它会根据请求获取我想要的数据,如下所示。

http://localhost:3000/api/projects

当我在pages/projects.js 内的getInitialProps() 内加载我请求该数据的页面时,它会显示我想要的数据,如下所示,到目前为止一切顺利。

console logs data coming through from custom express API route I have made

代码在这里:

pages/projects.js

import React, { Component } from "react";
import Layout from "../components/Layout";
import Siema from "siema";
import Head from "next/head";
import fetch from "isomorphic-unfetch";

export default class extends React.Component {
  componentDidMount() {
    this.siema = new Siema({
      loop: false
    });
  }

  prev = () => {
    this.siema.prev();
  };

  next = () => {
    this.siema.next();
  };

  render() {
    return (
      <Layout>
        <Head>
          <title>Jesal Patel | Projects</title>
        </Head>
        <div className="container">
          <section>
            <div className="projects">
              <div className="siema">
                <div>
                  <img src="(ignore this the img is showing on stackoverflow post.)" />
                  <div className="overlay">
                    <div id="overlay_title">Dextero</div>
                    <div id="overlay_description">
                      I developed a multi-touch mobile game for stroke patients
                      to rehabilitate their finger coordination and dexterity.
                    </div>
                    <div id="overlay_tech">Java, Android, LibGDX, SQLite</div>
                  </div>
                </div>
              </div>
              <div />

              <button onClick={this.prev}>Prev</button>
              <button onClick={this.next}>Next</button>
            </div>
          </section>
        </div>
      </Layout>
    );
  }

  static async getInitialProps({ req }) {
    //This fetch is the reason why my project won't build
    const result = await fetch("http://localhost:3000/api/projects");
    const projects = await result.json();

    console.log(projects);

    return { projects };
  }
}

问题:

现在问题开始于我运行next-build 并在此期间引发以下错误:编辑:我没有正确粘贴错误。注意:我运行 now-buildscript 导出项目,这是我的问题,是导致我出现问题的原因

   I:\Next.js\website>npm run now-build

> website@1.0.0 now-build I:\Next.js\website
> next build && next export -o dist

Creating an optimized production build ...

Compiled successfully.

 ┌ /
 ├ /_app
 ├ /_document
 ├ /_error
 ├ /contact
 └ /projects

> using build directory: I:\Next.js\website\.next
  copying "static" directory
  copying "static build" directory
> No "exportPathMap" found in "next.config.js". Generating map from "./pages"
  launching 11 threads with concurrency of 10 per thread
[====-] 4/5 80% 160/s 0.0s { FetchError: request to http://localhost:3000/api/projects failed, reason: connect ECONNREFUSED 127.0.0.1:3000
    at ClientRequest.<anonymous> (I:\Next.js\website\node_modules\node-fetch\lib\index.js:1444:11)
    at ClientRequest.emit (events.js:189:13)
    at Socket.socketErrorListener (_http_client.js:392:9)
    at Socket.emit (events.js:189:13)
    at emitErrorNT (internal/streams/destroy.js:82:8)
    at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
    at process._tickCallback (internal/process/next_tick.js:63:19)
  message:
   'request to http://localhost:3000/api/projects failed, reason: connect ECONNREFUSED 127.0.0.1:3000',
  type: 'system',
  errno: 'ECONNREFUSED',
  code: 'ECONNREFUSED' }
{ message:
   'request to http://localhost:3000/api/projects failed, reason: connect ECONNREFUSED 127.0.0.1:3000',
  type: 'system',
  errno: 'ECONNREFUSED',
  code: 'ECONNREFUSED' }
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! website@1.0.0 now-build: `next build && next export -o dist`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the website@1.0.0 now-build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Jesal\AppData\Roaming\npm-cache\_logs\2019-03-19T04_10_45_930Z-debug.log

我知道这是由于const result = await fetch("http://localhost:3000/api/projects"); 这一行,但我不知道该怎么做才能使其构建。我是 MEAN 堆栈的新手。我不确定我是否必须在全球某处外部创建该路由才能正常工作?我不知道这是否会解决它或是否是其他问题。

我在这个应用程序中使用了 Express 和 Mongoose,它们的代码可以在下面找到,以及 package.jsonnext.config.js 文件。

服务器/index.js

const express = require("express");
const next = require("next");
const bodyParser = require("body-parser");
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
const routes = require("./routes/index.js");
var mongoose = require("mongoose");
const PORT = process.env.PORT || 3000;

const dbName = "MySite";
const MONGO_URL =
  "mongodb+srv://admin:<hidden for privacy>@cluster0-5cjs1.mongodb.net/MySite?retryWrites=true";

app
  .prepare()
  .then(() => {
    mongoose.connect(MONGO_URL, { useNewUrlParser: true });

    mongoose.Promise = global.Promise;

    mongoose.connection.on("open", function() {
      console.log("mongodb is connected!!");
    });

    const db = mongoose.connection;

    model = db.modelNames();

    db.on("error", console.error.bind(console, "MongoDB connection error:"));

    const server = express();
    server.use(bodyParser.json());
    server.use(bodyParser.urlencoded({ extended: true }));
    server.use("/api", routes);

    server.use((req, res, next) => {
      // Also expose the MongoDB database handle so Next.js can access it.
      req.db = db;
      next();
    });

    server.get("*", (req, res) => {
      return handle(req, res);
    });

    server.listen(PORT, () => {
      console.log("Server is up and running on port number " + PORT);
    });
  })
  .catch(ex => {
    console.error(ex.stack);
    process.exit(1);
  });

server/routes/index.js

const express = require("express");
const router = express.Router();

const project_controller = require("../controllers/project_controller");

router.get("/projects", project_controller.projects_list);

module.exports = router;

server/models/project_schema.js

var mongoose = require("mongoose");

var Schema = mongoose.Schema;

var ProjectSchema = new Schema(
  {
    name: String,
    description: String,
    tech: String
  },
  { collection: "project" }
);

module.exports = mongoose.model("Project", ProjectSchema);

服务器/控制器/project_controller.js

const Project = require("../models/project_schema");

exports.test = function(req, res) {
  res.send("Greetings from the Test controller!");
};

exports.projects_list = function(req, res) {
  var documents = Project.find({}, function(err, docs) {
    if (err) throw err;
    res.send(docs);
    return docs;
  });
};

exports.project_create = function(req, res) {
  let project = new Project({
    name: req.body.name,
    description: req.body.description,
    tech: req.body.tech
  });

  project.save(function(err, project) {
    if (err) {
      console.log("Unsuccessful");
    }
    console.log("Saved!");
  });
};

package.json

{
  "name": "website",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "nodemon server/index.js",
    "now-build": "next build && next export -o dist",
    "build": "next build",
    "start": "next start -p 8000"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@engineerapart/nextscript": "^1.0.2",
    "@zeit/next-css": "^1.0.1",
    "@zeit/next-typescript": "^1.1.1",
    "body-parser": "^1.18.3",
    "bootstrap": "^4.3.1",
    "co": "^4.6.0",
    "cross-env": "^5.2.0",
    "express": "^4.16.4",
    "file-loader": "^3.0.1",
    "isomorphic-unfetch": "^3.0.0",
    "jquery": "^3.3.1",
    "mongodb": "^3.1.13",
    "mongoose": "^5.4.19",
    "next": "^8.0.4-canary.10",
    "next-compose-plugins": "^2.1.1",
    "next-images": "^1.0.4",
    "nodemon": "^1.18.10",
    "react": "^16.8.3",
    "react-dom": "^16.8.3",
    "react-slick": "^0.23.2",
    "siema": "^1.5.1",
    "superagent": "^4.1.0",
    "url-loader": "^1.1.2"
  }
}

next.config.js

const withCSS = require("@zeit/next-css");
const withImages = require("next-images");
const withPlugins = require("next-compose-plugins");

module.exports = {
  crossOrigin: "anonymous"
};

module.exports = withPlugins([withImages, withCSS]);

module.exports = withImages();

// module.exports = withCSS();

module.exports = {
  target: "serverless"
};

module.exports = withCSS({
  webpack: function(config) {
    config.module.rules.push({
      test: /\.(eot|woff|woff2|ttf|svg|png|jpg|gif)$/,
      use: {
        loader: "url-loader",
        options: {
          limit: 100000,
          name: "[name].[ext]"
        }
      }
    });
    return config;
  }
});

更新:这是对 Prabhakar Pandey 响应的更新,让你们知道,我在运行 now-buildcommand 时总是杀死服务器,另外,正如我之前提到的,要非常清楚在我第一次编辑这篇文章时,它是该命令的第二部分,它因错误而失败,即next export -o distnot next build,它工作正常!另外,我使用的是 Windows 操作系统而不是 Mac 操作系统。

【问题讨论】:

  • 我知道为时已晚,但可能对其他读者有用。因为您获取 localhost -您需要在构建项目时运行服务器。如此简单地打开两个终端,一种类型next run dev 运行开发服务器,然后在第二个控制台类型next run build(或您的preffer 命令)。
  • @northernwind 实际上解决了我遇到的同样问题,不知道为什么你需要 npm run dev 同时
  • @MaximeGhéraille 想不通 - 你问的是你的问题或我的情况。如果您有同样的问题 - 那是因为您需要运行 _next 服务器,以“即时”操作 url 和构建页面。

标签: javascript node.js express mongoose next.js


【解决方案1】:

发生这种情况是因为您想在已被使用的端口上运行应用程序。

您可以使用以下命令检查端口上运行的应用程序:


For macOS El Capitan and newer (or if your netstat doesn't support -p), use lsof

sudo lsof -i tcp:3000 

For Centos 7 use

netstat -vanp --tcp | grep 3000

Also if wnat to kill any process you can use

kill -9 `PID`

when port is empty you try your application by rebuilding it should work

【讨论】:

  • 这不是问题所在。在运行now-build 命令时,我总是杀死服务器,注意:这是该命令的第二部分失败并出现错误,即next export -o dist。另外,我在 Windows 上
猜你喜欢
  • 2020-09-14
  • 2023-01-26
  • 2020-01-28
  • 1970-01-01
  • 2021-01-04
  • 2018-10-26
  • 2019-07-07
  • 2016-02-16
  • 2014-05-13
相关资源
最近更新 更多