简体   繁体   English

为什么我的带有 express 和 nodejs 的 RestFul API 每天都崩溃?

[英]Why my RestFul API with express and nodejs crashed everyday?

I have restful api with express and nodejs but this api crashed every time.我有带有 express 和 nodejs 的宁静 api,但是这个 api 每次都崩溃了。 So.. I have one function for datatime.所以..我有一个数据时间功能。 This function will replace date in the url address everytime to current datetime.. Im not sure but may be when the current date is change with the new current date the API crashed..此函数将每次将 url 地址中的日期替换为当前日期时间.. 我不确定但可能是当当前日期与新的当前日期更改时 API 崩溃了..

I see this error message on the console:我在控制台上看到此错误消息:

events.js:187
      throw er; // Unhandled 'error' event
      ^

Error: read ECONNRESET
    at TCP.onStreamRead (internal/stream_base_commons.js:201:27)
Emitted 'error' event on Connection instance at:
    at Connection._handleProtocolError (C:\Users\Admin\Desktop\node-express\node_modules\mysql\lib\Connection.js:426:8)
    at Protocol.emit (events.js:210:5)
    at Protocol._delegateError (C:\Users\Admin\Desktop\node-express\node_modules\mysql\lib\protocol\Protocol.js:398:10)
    at Protocol.handleNetworkError (C:\Users\Admin\Desktop\node-express\node_modules\mysql\lib\protocol\Protocol.js:371:10)
    at Connection._handleNetworkError (C:\Users\Admin\Desktop\node-express\node_modules\mysql\lib\Connection.js:421:18)
    at Socket.emit (events.js:210:5)
    at emitErrorNT (internal/streams/destroy.js:92:8)
    at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
    at processTicksAndRejections (internal/process/task_queues.js:80:21) {
  errno: 'ECONNRESET',
  code: 'ECONNRESET',
  syscall: 'read',
  fatal: true
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! express-api@1.0.0 start: `node server.js`
npm ERR!
npm ERR! Failed at the express-api@1.0.0 start 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\Admin\AppData\Roaming\npm-cache\_logs\2019-12-29T04_48_17_190Z-debug.log

So this is the code for api.. Its very simple.. but I dont know how to fix this error.所以这是api的代码..它非常简单..但我不知道如何修复这个错误。 When I wake up and try to see the data from the API every time the API is crashed.当我醒来并尝试在每次 API 崩溃时查看来自 API 的数据时。

This is the code from the api:这是来自api的代码:

// Create express app
var express = require("express")
var app = express()
var mysql = require('mysql')
var express = require("express")
var cors = require('cors')

app.use(cors())

// Server port
var HTTP_PORT = 8000

// Start server
app.listen(HTTP_PORT, () => {
  console.log("Server running on port %PORT%".replace("%PORT%", HTTP_PORT))
});

var con = mysql.createConnection({
  host: "192.168.0.1",
  port: "1234",
  user: "username",
  password: "password"
});

let aladinModel = '';
let aladinModelStations = '';


function formatDate(date) {
  var d = new Date(date),
      month = '' + (d.getMonth() + 1),
      day = '' + d.getDate(),
      year = d.getFullYear();

  if (month.length < 2) 
      month = '0' + month;
  if (day.length < 2) 
      day = '0' + day;

  return [year, month, day].join('-');
}

var dateNow = formatDate(Date());

app.route('/')
  .get(function (req, res) {
    // omitted
    res.setHeader('Access-Control-Allow-Origin', '*', 'Cache-Control', 'private, no-cache, no-store, must-revalidate');
    const date = req.query.date;
    const id = req.query.id;
    const daysForward = req.query.daysForward;

    try {
      const query = `CALL aladin_surfex.Get_mod_cell_values_meteogram_cell('${dateNow}', ${id}, ${daysForward})`;
      con.query(query, function (err, result, fields) {
        if (err) throw err;
        aladinModel = result;

      });
      res.json({ aladinModel })

    } catch (error) { 
      console.log("Error query database!!!");
    }
  });

app.route('/stations')
  .get(function (req, res) {
    // omitted
    res.setHeader('Access-Control-Allow-Origin', '*');
    try {
      const query2 = `SELECT Station,Ime FROM aladin_surfex.stations_cells;`;
      con.query(query2, function (err, result2, fields) {
        if (err) throw err;
        aladinModelStations = result2;
      });
      res.json({ aladinModelStations })
    } catch (error) {
      console.log("Error query database!!!");
    }
  });

app.use(function (req, res) {
  res.status(404);
});

I try to remove the cashe, to update npm, to restart the computer.我尝试删除现金,更新 npm,重新启动计算机。 But without the result.但没有结果。 With nodemon crashed the same.. What can I do ?与 nodemon 崩溃相同.. 我能做什么? How can to fix that ?如何解决?

The error seems to be related to the connection to mysql.该错误似乎与与 mysql 的连接有关。

As mysqljs documentation ( https://github.com/mysqljs/mysql#error-handling ):作为 mysqljs 文档( https://github.com/mysqljs/mysql#error-handling ):

Note: 'error' events are special in node.注意:'error' 事件在 node.js 中是特殊的。 If they occur without an attached listener, a stack trace is printed and your process is killed.如果它们在没有附加侦听器的情况下发生,则会打印堆栈跟踪并终止您的进程。

You shuld intercept the connection error like this:您应该像这样拦截连接错误:

connection.on('error', function(err) {
  console.log(err.code); // 'ER_BAD_DB_ERROR'
});

so you can investigate when and why the error occours and eventually you can recreate the connection when a problem occurs.因此您可以调查错误发生的时间和原因,最终您可以在出现问题时重新创建连接。

  1. Move app.listen to the bottom of the file, after you declare all the routes and connect to the database.在声明所有路由并连接到数据库后,将app.listen移至文件底部。

  2. Use app.get('route', function...) (more on that in the Express docs)使用app.get('route', function...) (更多关于Express 文档)

  3. Move res.json() inside the callback function for each database query.res.json()移动到每个数据库查询的回调函数中。 The result will come back asynchronously so will not be accessible outside the function.结果将异步返回,因此无法在函数外部访问。 If you're new to async and callbacks in Javascript I'd recommend googling them and you'll find a ton of reading materials.如果您不熟悉 Javascript 中的异步和回调,我建议您使用谷歌搜索它们,您会发现大量阅读材料。

  4. Initialize your variables, eg const aladinModel = ...初始化您的变量,例如const aladinModel = ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM