[英]Node.js - Defined a function yet throws an error
我正在開發一個聊天應用程序。 我正在使用快速驗證器。
const express = require('express');
const validator = require('express-validator');
const container = require('./container');
function ConfigureExpress(app){
app.use(express.static('public'));
app.use(cookieParser());
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(validator());
app.use(session({
secret: 'thisisasecretkey',
resave: true,
saveInitialized: true,
store: new MongoStore({mongooseConnection: mongoose.connection})
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
}
這是我運行 nodemon 服務器時拋出的錯誤:
C:\Users\Utkarsh Rai\aqchat\server.js:49
app.use(validator());
^
TypeError: validator is not a function
我試圖解決這個問題,但我無法理解我哪里出錯了。 我試着搜索這個問題。
您使用 express-validator 的方式不正確。 您必須從 express-validator 導入驗證結果。
const { validationResult } = require('express-validator')
定義你自己的中間件
const validate = (req, res, next) => {
const errors = validationResult(req)
if (errors.isEmpty()) {
return next()
}
//do whatever you want with errors
return res.status(500).json({
errors: errors,
})
}
並在你的 app.js 中使用這個中間件
從文檔:
// ...rest of the initial code omitted for simplicity.
const { check, validationResult } = require('express-validator');
app.post('/user', [
// username must be an email
check('username').isEmail(),
// password must be at least 5 chars long
check('password').isLength({ min: 5 })
], (req, res) => {
// Finds the validation errors in this request and wraps them in an object with handy functions
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
User.create({
username: req.body.username,
password: req.body.password
}).then(user => res.json(user));
});
因此,您需要創建自己的驗證方法,例如:
function ConfigureExpress(app){
app.use(express.static('public'));
app.use(cookieParser());
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
//Our validator code
app.use([
/*
ex. validator.check('username').isAlphanumeric()
*/
]);
app.use(session({
secret: 'thisisasecretkey',
resave: true,
saveInitialized: true,
store: new MongoStore({mongooseConnection: mongoose.connection})
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
}
express-validator 在最新版本中更改規則
請看一下點擊這里
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.