简体   繁体   中英

Nodejs require doesn't work

Why does the following code not work

const {express} = require('express');

const router = express.Router();

Unresolved function or method Router

but this work

const express = require('express');

and if I want to do this require, what should I do.. two method in one require

const {validationResult, check} = require('express-validator/check');

node -v // v8.3.0

I'm trying to use this.. https://github.com/ctavan/express-validator#usage

Why does the following code not work

const {express} = require('express');

const router = express.Router();

You're using destructuring to extract a property that's not there. Your code is effectively doing this:

const temp = require('express');
const express = temp.express;

The object returned by require('express') has several properties, but .express is not one of them, so you end up setting express to undefined. And then when you call express.Router(), you get the error.

Your code that works is just saving the whole object, and then accessing it with the correct property names. You can keep that code, or if you know that you only are interested in the router you can do:

const {Router} = require('express');
const router = Router();

which would be pretty much the same as:

const express = require('express');
const Router = express.Router;
const router = Router();

and if I want to do this require, what should I do.. two method in one require

const {validationResult, check} = require('express-validator/check');

I'm not familiar with what that library exports. If you know that the object has both a validationResult and a check and that those are the only things you care about, then your code looks fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM