【发布时间】:2020-03-26 02:57:23
【问题描述】:
这是我的 NodeJS 应用程序。我已经注释掉了一些部分以缩小问题范围。
const functions = require('firebase-functions');
const express = require('express');
// const path = require('path');
// const bodyParser = require('body-parser');
const app = express();
// const gameAPI = require('./routes/apiv1');
const startTime = Date.now();
Error.stackTraceLimit = Infinity;
console.log("Server Started");
// app.use('/node_modules',express.static(path.join(__dirname, 'node_modules')));
// app.use(bodyParser.json());
// app.use(bodyParser.urlencoded({ extended: true }));
app.use((err, req, res, next) => {
res.status(500).send();
});
// app.use('/v1.0', gameAPI);
app.get('/', (req, res)=>{
res.send(`App started ${(Date.now() - startTime)/1000}s ago`);
});
exports.app = functions.https.onRequest(app);
当我发送无效的 JSON 时
{
"ign":"XX"
"allies": "5"
}
应用程序崩溃。
[11:21:31]{}firebase-test:sulochana$ firebase serve --only functions,hosting
✔ functions: Using node@8 from host.
✔ functions: Emulator started at http://localhost:5001
i functions: Watching "/home/sulochana/Documents/firebase-test/functions" for Cloud Functions...
i hosting: Serving hosting files from: public
✔ hosting: Local server: http://localhost:5000
> Server Started
✔ functions[app]: http function initialized (http://localhost:5001/scrim-engine/us-central1/app).
[hosting] Rewriting /v1.0/dota/queue to http://localhost:5001/scrim-engine/us-central1/app for local Function app
> Server Started
i functions: Beginning execution of "app"
> SyntaxError: Unexpected string in JSON at position 15
> at JSON.parse (<anonymous>)
> at parse (/usr/lib/node_modules/firebase-tools/node_modules/body-parser/lib/types/json.js:89:19)
> at /usr/lib/node_modules/firebase-tools/node_modules/body-parser/lib/read.js:121:18
> at invokeCallback (/usr/lib/node_modules/firebase-tools/node_modules/raw-body/index.js:224:16)
> at done (/usr/lib/node_modules/firebase-tools/node_modules/raw-body/index.js:213:7)
> at IncomingMessage.onEnd (/usr/lib/node_modules/firebase-tools/node_modules/raw-body/index.js:273:7)
> at emitNone (events.js:111:20)
> at IncomingMessage.emit (events.js:208:7)
> at endReadableNT (_stream_readable.js:1064:12)
> at _combinedTickCallback (internal/process/next_tick.js:139:11)
如何处理这个异常。这将允许外部用户使应用程序崩溃
【问题讨论】:
-
您究竟是如何发送此 JSON 的?请编辑问题以具体说明您的客户在做什么,以及与之相关的任何代码。您可能在客户端或后端做错了什么。理想情况下,我们应该在问题本身中拥有一切必要的东西来重现问题。
-
解析客户端json请求时添加try catch
-
@DougStevenson 我通过邮递员发送这个。无论客户端做什么,应用程序都不应崩溃。
-
您真正关心的是什么?如果有人发送无效的 JSON,是否会停止按您预期的方式工作?您要解决什么具体问题?
-
如果有人发送了无效的JSON,会导致服务器重启。此服务器不是无状态的
标签: javascript node.js json firebase google-cloud-functions