Оператор return в /routes/todos.js не останавливает выполнение моего приложения. Вместо этого выполняется функция «Обработка ошибок 404» app.use(), которая размещается после app.use("/todos", todoRoutes).
Когда я посещаю маршрут localhost:3001/todos/addTodo, отображается правильный ответ «Спасибо за отправку формы», но в моей консоли Вызов console.error() из нижней части app.js отображается со стеком ошибок, НО оператор return в общем обработчике НЕ возвращается пользователю.
Почему мое приложение продолжает работу с обработчиком 404, хотя я возвращаю res.send() в своем маршруте? Не думаю, что подобное происходит в других моих приложениях.
app.js
"use strict";
const express = require("express");
const cors = require("cors");
const helmet = require("helmet");
const { NotFoundError } = require("./expressError");
const todoRoutes = require('./routes/todos')
const app = express();
app.use(cors());
app.use(helmet({ crossOriginResourcePolicy: false }));
app.use(express.json());
app.use("/todos", todoRoutes)
// so we don't get the "not found" error in our console for the favicon
app.get("/favicon.ico", (req, res) => res.sendStatus(204));
// our home page of our backend, just send back a 200 response
app.get("/", (req, res) => res.sendStatus(200));
/** Handle 404 errors -- this will catch everything that makes it this far */
app.use(function (req, res, next) {
console.log("hit the 404 use".brightCyan)
return next(new NotFoundError());
});
/** Generic error handler; anything unhandled goes here. */
/** express knows that a function is an error handler because
* the function has 4 parameters */
app.use(function (err, req, res, next) {
console.log("hit the generic use".brightCyan)
if (process.env.NODE_ENV !== "test") console.error(err.stack);
const status = err.status || 500;
const message = err.message;
console.log(status, message)
return res.status(status).json({
error: { message, status },
});
});
module.exports = app;
routes/todos.js
const express = require('express');
const router = express.Router();
router.get('/addTodo', async function (req, res) {
console.log('==> running todo route'.brightCyan);
return res.send("Thanks for submitting the form");
})
module.exports = router;
Подробнее здесь: https://stackoverflow.com/questions/797 ... ion-of-the
Почему оператор return в моем маршруте express.js не останавливает выполнение промежуточного программного обеспечения, р ⇐ Javascript
Форум по Javascript
1759975833
Anonymous
Оператор return в [b]/routes/todos.js[/b] не останавливает выполнение моего приложения. Вместо этого выполняется функция «Обработка ошибок 404» app.use(), которая размещается после app.use("/todos", todoRoutes).
Когда я посещаю маршрут localhost:3001/todos/addTodo, отображается правильный ответ «Спасибо за отправку формы», но в моей консоли Вызов console.error() из нижней части [b]app.js[/b] отображается со стеком ошибок, НО оператор return в общем обработчике НЕ возвращается пользователю.
Почему мое приложение продолжает работу с обработчиком 404, хотя я возвращаю res.send() в своем маршруте? Не думаю, что подобное происходит в других моих приложениях.
[b]app.js[/b]
"use strict";
const express = require("express");
const cors = require("cors");
const helmet = require("helmet");
const { NotFoundError } = require("./expressError");
const todoRoutes = require('./routes/todos')
const app = express();
app.use(cors());
app.use(helmet({ crossOriginResourcePolicy: false }));
app.use(express.json());
app.use("/todos", todoRoutes)
// so we don't get the "not found" error in our console for the favicon
app.get("/favicon.ico", (req, res) => res.sendStatus(204));
// our home page of our backend, just send back a 200 response
app.get("/", (req, res) => res.sendStatus(200));
/** Handle 404 errors -- this will catch everything that makes it this far */
app.use(function (req, res, next) {
console.log("hit the 404 use".brightCyan)
return next(new NotFoundError());
});
/** Generic error handler; anything unhandled goes here. */
/** express knows that a function is an error handler because
* the function has 4 parameters */
app.use(function (err, req, res, next) {
console.log("hit the generic use".brightCyan)
if (process.env.NODE_ENV !== "test") console.error(err.stack);
const status = err.status || 500;
const message = err.message;
console.log(status, message)
return res.status(status).json({
error: { message, status },
});
});
module.exports = app;
[b]routes/todos.js[/b]
const express = require('express');
const router = express.Router();
router.get('/addTodo', async function (req, res) {
console.log('==> running todo route'.brightCyan);
return res.send("Thanks for submitting the form");
})
module.exports = router;
Подробнее здесь: [url]https://stackoverflow.com/questions/79785967/why-is-the-return-statement-in-my-express-js-route-not-stopping-execution-of-the[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия