[英]Confused about 'use strict' in JavaScript/nodejs
當我在代碼中添加一個linter時,我注意到關於'use strict';
的很多錯誤'use strict';
所以我將這一行添加到很多文件中。 但是,這在我的主要app.js
文件中破壞了一些代碼,如下所示:
'use strict';
var express = require('express');
var timeout = require('connect-timeout');
//var logger = require('morgan');
var requireDir = require('require-dir');
var app = express();
// Load all the routes in the routes file into app middleware
// This assumes that the route exports an express.Router() object
var routes = requireDir('./routes');
for (var i in routes) app.use('/', routes[i]);
// Set the timeout
app.use(timeout('5s'));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = 'ERROR: Invalid request to the server';
err.status = 404;
next(err);
});
if (!module.parent) {
app.listen(3000);
console.log('engine-map-service opend on port 3000');
}
它返回以下error
堆棧:
TypeError: Cannot assign to read only property 'status' of ERROR: Invalid request to the server
at /usr/src/app/app.js:21:14
at Layer.handle [as handle_request] (/usr/src/app/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/usr/src/app/node_modules/express/lib/router/index.js:312:13)
at /usr/src/app/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/usr/src/app/node_modules/express/lib/router/index.js:330:12)
at next (/usr/src/app/node_modules/express/lib/router/index.js:271:10)
at /usr/src/app/node_modules/connect-timeout/index.js:64:5
at Layer.handle [as handle_request] (/usr/src/app/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/usr/src/app/node_modules/express/lib/router/index.js:312:13)
at /usr/src/app/node_modules/express/lib/router/index.js:280:7
use strict
到底是什么? 我已經閱讀了幾篇文章,但是關於如何改變開發人員的行為以及何時應該或不應該使用它,我沒有深入了解。 我發現有不止一篇文章建議use strict
開始每個js
文件,但顯然有些情況我不見了。
在Java中,“嚴格使用”的用途廣泛涉及use strict
的用法, 其背后的原因是什么? 。
在您的特定情況下,它捕獲的TypeError
除非在運行時發生某種條件,否則否則不會拋出該錯誤。
在錯誤處理程序中,您將創建一個名為err
的字符串,然后嘗試為其分配屬性。 您不能將屬性分配給字符串。
如果要創建同時包含消息和狀態的錯誤對象,則可以執行以下操作:
app.use(function(req, res, next) {
var err = {
message: 'ERROR: Invalid request to the server',
status: 404
};
next(err);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.