Nodejs (express) 运行 但请求不工作

Nodejs (express) running but requests not working

我运行我的项目后端'server.js'(快递)。它工作正常,没有任何问题。但是我从 Postman 或其他应用程序发送请求,我无法得到任何响应或错误。仅加载。 有时它工作正常,我正确地收到所有请求,但几分钟或几小时后我无法收到任何请求响应。 请帮我。是什么导致这个问题? 我正在使用 Reactjs、Nodejs (express)

在您的 staring 文件中使用此代码作为全局错误处理。您将获得所有错误结果 json。

因为您的 url 中可能有拼写错误。因此,有了这段代码,您将得到 .. not fount error res ... as json。

    
    // route not found
    app.use((req, res, next) => {
     const error = new Error('Not found');
     error.message = 'Invalid route';
     error.status = 404;
     next(error);
    });
   // log errors to console
    app.use(logErrors);
     //
    app.use(clientErrorHandler);
    app.use((error, req, res, next) => {
    res.status(error.status || 500);
      return res.json({
      status:error.status || 500,
      message: error.message,
      error: {
      error: error.message,
      },
    });
   });

// log errors to console
function logErrors(err, req, res, next) {
  console.error(err.stack);
  next(err);
}
// error handling for xhr request
function clientErrorHandler(err, req, res, next) {
  if (req.xhr) {
    //console.log('xhr request');
    res.status(400).send({status: 400, message: "Bad request from client", error: err.message });
  } else {
    next(err);
  }
}

let port = process.env.PORT || 8081;
app.listen(port, () => {
  console.log(`Listening on port ${port}`);
});

这是一个简单的express js使用方法,或许你可以试试

首先,您必须输入应用的详细信息。

npm init

其次,您必须安装 Body Parser 和 Express

npm install body-parser express --save

第三,将这段代码放到你的主js中(例如server.js或index.js你在npm init中输入的内容)

const BodyParser = require( 'body-parser' );
const Express = require( 'express' );
const App = Express();

// Parse request of content-type - application/x-www-form-urlencoded
App.use( BodyParser.urlencoded( { extended: false } ) );

// Parse request of content-type - application/json
App.use( BodyParser.json() );

App.listen( 3000, () => {
 console.log( "Server Run:" + 3000 );
} );

App.get( '/', function( req, res ) {
 res.json( {
  status: "OK"
 } );
} );

App.get( '/test', function( req, res ) {
 res.json( {
  status: "Hehehe Test"
 } );
} );

四、启动节点

node server.js

现在,您可以在浏览器中访问您的代码

http://localhost:3000/
http://localhost:3000/test