Я создаю Node.js + Express API, я получаю сообщение об ошибке в приложении публикации без ошибок в коде vs.
Я создаю Node.js + Express API для регистрации пользователей. Я использую асинхронный контроллер, завернутый в специальную оболочку обработки ошибок (catchAsyncError), чтобы избежать написания повторяющихся блоков try/catch.
отправить запрос — http://localhost:4000/api/v1/user/register
{
"name": "Harsh Mishra",
"email": "harsh.testing@example.com",
"phone": "+911234567890",
"verificationMethod": "email",
"password": "TestPass123"
}
ошибка -
{
"success": false,
"message": "next is not a function"
}
userController.js
import { ErrorHandler } from "../middlewares/error.js";
import catchAsyncError from "../middlewares/catchAsyncError.js";
import { User } from "../models/userModel.js";
import { sendEmail } from "../utils/sendEmail.js";
import twilio from "twilio";
const client = twilio(process.env.TWILIO_SID, process.env.TWILIO_AUTH_TOKEN);
export const register = catchAsyncError(async (req, res, next) => {
const { name, email, phone, password, verificationMethod } = req.body;
// 1) Check required fields
if (!name || !email || !phone || !password || !verificationMethod) {
return next(new ErrorHandler("All fields are required", 400));
}
// 2) Phone number validation
const phoneRegex = /^\+91\d{10}$/;
if (!phoneRegex.test(phone)) {
return next(new ErrorHandler("Invalid phone number", 400));
}
// 3) Check if verified user already exists
const existingUser = await User.findOne({
$or: [{ email, accountVerified: true }, { phone, accountVerified: true }],
});
if (existingUser) {
return next(new ErrorHandler("Email or Phone is already used", 400));
}
// 4) Limit number of attempts for unverified users
const registerationAttemptsByUser = await User.find({
$or: [{ phone, accountVerified: false }, { email, accountVerified: false }],
});
if (registerationAttemptsByUser.length > 3) {
return next(
new ErrorHandler(
"You exceeded the maximum number of attempts (3). Please try again after an hour",
400
)
);
}
// 5) Create user
const userData = { name, email, phone, password };
const user = await User.create(userData);
// 6) Generate verification code
const verificationCode = await user.generateVerificationCode();
await user.save();
// 7) Send verification code (NOW includes next)
return sendVerificationCode(
verificationMethod,
verificationCode,
name,
email,
phone,
res,
next
);
});
// ---------------------------------------------------------------------
async function sendVerificationCode(
verificationMethod,
verificationCode,
name,
email,
phone,
res,
next
) {
try {
if (verificationMethod === "email") {
const message = generateEmailTemplate(verificationCode);
sendEmail({ email, subject: "Your Verification Code", message });
return res.status(200).json({
success: true,
message: `Verification email successfully sent to ${name}`,
});
}
// ------------------- PHONE CALL VERIFICATION -------------------
else if (verificationMethod === "phone") {
const spacedCode = verificationCode.toString().split("").join(" ");
await client.calls.create({
twiml: `Your verification code is ${spacedCode}`,
from: process.env.TWILIO_PHONE_NUMBER,
to: phone,
});
return res.status(200).json({
success: true,
message: `OTP sent`,
});
}
// ------------------- INVALID METHOD -------------------
else {
return next(new ErrorHandler("Invalid verification method", 400));
}
} catch (error) {
return next(error);
}
}
// ---------------------------------------------------------------------
function generateEmailTemplate(verificationCode) {
return `
Verification Code
body {
background-color: #f5f7fa;
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
color: #333;
}
.container {
max-width: 500px;
margin: 40px auto;
background: white;
border-radius: 10px;
padding: 25px;
box-shadow: 0px 4px 15px rgba(0,0,0,0.1);
}
.header {
text-align: center;
margin-bottom: 20px;
}
.header h2 {
color: #4a90e2;
font-size: 24px;
margin: 0;
}
.code-box {
background: #f0f4ff;
border-left: 4px solid #4a90e2;
padding: 15px;
font-size: 22px;
font-weight: bold;
text-align: center;
letter-spacing: 4px;
margin: 20px 0;
}
.footer {
margin-top: 20px;
font-size: 14px;
color: #777;
text-align: center;
}
Your Verification Code
Hello,
Use the verification code below to complete your signup process:
${verificationCode}
This code will expire in 15 minutes. Do not share it with anyone.
© ${new Date().getFullYear()} Your App Name. All rights reserved.
`;
}
catchAsync.js -
// middlewares/catchAsyncError.js
const catchAsyncError = (fn) => {
return (req, res, next) => {
Promise
.resolve(fn(req, res, next))
.catch(next)
}
}
export default catchAsyncError
userRoute.js --
import express from "express"
import { register } from "../controllers/userController.js"
const router = express.Router()
router.post("/register", register)
export default router
app.js -
import express from "express";
import {config} from "dotenv"
import cookieParser from "cookie-parser";
import cors from "cors"
import {connection} from "./database/dbconnection.js";
import { errorMiddleware } from "./middlewares/error.js";
import userRouter from "./routes/userRouter.js";
export const app = express();
config({path:"./config.env"});
app.use(cors({
origin: [process.env.FRONTEND_URL],
methods:["GET","POST","DELETE","PUT"],
credentials:true,
}))
app.use(cookieParser());
app.use(express.json());
app.use(express.urlencoded({extended:true}))
app.use("/api/v1/user",userRouter);
connection();
// use error middleware at last
// Express automatically calls errorMiddleware whenever an error occurs inside your routes.that why we do not call it only use it
app.use(errorMiddleware)
server.js -
import {app} from "./app.js"
app.listen(process.env.PORT,()=>{
console.log(`Server listening on port ${process.env.PORT}`);
})
dbconnection.js --
import mongoose from "mongoose"
export const connection = ()=>{
mongoose.connect(process.env.MONGO_URI,{
dbName:"MERN_AUTHENTICATION"
}).then(()=>{
console.log("Connected to the database");
}).catch(err=>{
console.log(`Some error occured while connnection ${err}`);
});
};
Подробнее здесь: https://stackoverflow.com/questions/798 ... in-node-js
Выразите «следующее не функция» в узле js ⇐ Javascript
Форум по Javascript
1764692909
Anonymous
Я создаю Node.js + Express API, я получаю сообщение об ошибке в приложении публикации без ошибок в коде vs.
Я создаю Node.js + Express API для регистрации пользователей. Я использую [b]асинхронный контроллер[/b], завернутый в [b]специальную оболочку обработки ошибок[/b] (catchAsyncError), чтобы избежать написания повторяющихся блоков try/catch.
отправить запрос — http://localhost:4000/api/v1/user/register
{
"name": "Harsh Mishra",
"email": "harsh.testing@example.com",
"phone": "+911234567890",
"verificationMethod": "email",
"password": "TestPass123"
}
ошибка -
{
"success": false,
"message": "next is not a function"
}
userController.js
import { ErrorHandler } from "../middlewares/error.js";
import catchAsyncError from "../middlewares/catchAsyncError.js";
import { User } from "../models/userModel.js";
import { sendEmail } from "../utils/sendEmail.js";
import twilio from "twilio";
const client = twilio(process.env.TWILIO_SID, process.env.TWILIO_AUTH_TOKEN);
export const register = catchAsyncError(async (req, res, next) => {
const { name, email, phone, password, verificationMethod } = req.body;
// 1) Check required fields
if (!name || !email || !phone || !password || !verificationMethod) {
return next(new ErrorHandler("All fields are required", 400));
}
// 2) Phone number validation
const phoneRegex = /^\+91\d{10}$/;
if (!phoneRegex.test(phone)) {
return next(new ErrorHandler("Invalid phone number", 400));
}
// 3) Check if verified user already exists
const existingUser = await User.findOne({
$or: [{ email, accountVerified: true }, { phone, accountVerified: true }],
});
if (existingUser) {
return next(new ErrorHandler("Email or Phone is already used", 400));
}
// 4) Limit number of attempts for unverified users
const registerationAttemptsByUser = await User.find({
$or: [{ phone, accountVerified: false }, { email, accountVerified: false }],
});
if (registerationAttemptsByUser.length > 3) {
return next(
new ErrorHandler(
"You exceeded the maximum number of attempts (3). Please try again after an hour",
400
)
);
}
// 5) Create user
const userData = { name, email, phone, password };
const user = await User.create(userData);
// 6) Generate verification code
const verificationCode = await user.generateVerificationCode();
await user.save();
// 7) Send verification code (NOW includes next)
return sendVerificationCode(
verificationMethod,
verificationCode,
name,
email,
phone,
res,
next
);
});
// ---------------------------------------------------------------------
async function sendVerificationCode(
verificationMethod,
verificationCode,
name,
email,
phone,
res,
next
) {
try {
if (verificationMethod === "email") {
const message = generateEmailTemplate(verificationCode);
sendEmail({ email, subject: "Your Verification Code", message });
return res.status(200).json({
success: true,
message: `Verification email successfully sent to ${name}`,
});
}
// ------------------- PHONE CALL VERIFICATION -------------------
else if (verificationMethod === "phone") {
const spacedCode = verificationCode.toString().split("").join(" ");
await client.calls.create({
twiml: `Your verification code is ${spacedCode}`,
from: process.env.TWILIO_PHONE_NUMBER,
to: phone,
});
return res.status(200).json({
success: true,
message: `OTP sent`,
});
}
// ------------------- INVALID METHOD -------------------
else {
return next(new ErrorHandler("Invalid verification method", 400));
}
} catch (error) {
return next(error);
}
}
// ---------------------------------------------------------------------
function generateEmailTemplate(verificationCode) {
return `
Verification Code
body {
background-color: #f5f7fa;
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
color: #333;
}
.container {
max-width: 500px;
margin: 40px auto;
background: white;
border-radius: 10px;
padding: 25px;
box-shadow: 0px 4px 15px rgba(0,0,0,0.1);
}
.header {
text-align: center;
margin-bottom: 20px;
}
.header h2 {
color: #4a90e2;
font-size: 24px;
margin: 0;
}
.code-box {
background: #f0f4ff;
border-left: 4px solid #4a90e2;
padding: 15px;
font-size: 22px;
font-weight: bold;
text-align: center;
letter-spacing: 4px;
margin: 20px 0;
}
.footer {
margin-top: 20px;
font-size: 14px;
color: #777;
text-align: center;
}
Your Verification Code
Hello,
Use the verification code below to complete your signup process:
${verificationCode}
This code will expire in [b]15 minutes[/b]. Do not share it with anyone.
© ${new Date().getFullYear()} Your App Name. All rights reserved.
`;
}
catchAsync.js -
// middlewares/catchAsyncError.js
const catchAsyncError = (fn) => {
return (req, res, next) => {
Promise
.resolve(fn(req, res, next))
.catch(next)
}
}
export default catchAsyncError
userRoute.js --
import express from "express"
import { register } from "../controllers/userController.js"
const router = express.Router()
router.post("/register", register)
export default router
app.js -
import express from "express";
import {config} from "dotenv"
import cookieParser from "cookie-parser";
import cors from "cors"
import {connection} from "./database/dbconnection.js";
import { errorMiddleware } from "./middlewares/error.js";
import userRouter from "./routes/userRouter.js";
export const app = express();
config({path:"./config.env"});
app.use(cors({
origin: [process.env.FRONTEND_URL],
methods:["GET","POST","DELETE","PUT"],
credentials:true,
}))
app.use(cookieParser());
app.use(express.json());
app.use(express.urlencoded({extended:true}))
app.use("/api/v1/user",userRouter);
connection();
// use error middleware at last
// Express automatically calls errorMiddleware whenever an error occurs inside your routes.that why we do not call it only use it
app.use(errorMiddleware)
server.js -
import {app} from "./app.js"
app.listen(process.env.PORT,()=>{
console.log(`Server listening on port ${process.env.PORT}`);
})
dbconnection.js --
import mongoose from "mongoose"
export const connection = ()=>{
mongoose.connect(process.env.MONGO_URI,{
dbName:"MERN_AUTHENTICATION"
}).then(()=>{
console.log("Connected to the database");
}).catch(err=>{
console.log(`Some error occured while connnection ${err}`);
});
};
Подробнее здесь: [url]https://stackoverflow.com/questions/79836101/express-next-is-not-a-function-in-node-js[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия