Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs + express: Cors is not a function

Been working fine up until this morning and now, suddenly i am getting a type error stating that Cors is not a function

My code

import * as Cors from "cors";
...

const corsOptions: Cors.CorsOptions = {
    allowedHeaders: ["Origin", "X-Requested-With", "Content-Type", "Accept", "X-Access-Token", "Authorization"],
    credentials: true,
    methods: "GET,HEAD,OPTIONS,PUT,PATCH,POST,DELETE",
    origin: "*",
    preflightContinue: true
};

createConnection(ormConfig).then(async connection => {
    // run pending migrations
    await connection.runMigrations();
    // create express server
    const app = express();
    app.use(bodyParser.json({limit: "50mb"}));
    app.use(bodyParser.urlencoded({limit: "50mb", extended: true}));
    // register cors
    app.use(Cors(corsOptions)); //<---error occurs here
    // register all controllers
    useExpressServer(app, {
        routePrefix: "/api",
        controllers: [
            __dirname + "/controllers/**/*{.js,.ts}"
        ],
        authorizationChecker: async (action: any, roles: string[]) => {
            return JwtAuthorizationMiddleware.checkIsAuthorized(action, roles);
        },
        currentUserChecker: async (actions: any) => {
            return JwtAuthorizationMiddleware.extractUserFromJwtToken(actions);
        }
    });

    // start the express server
    const port: number = +(process.env.PORT || 44320);
    app.listen(port, (err: Error) => {
        console.log(`App listening on port ${port}`);
        console.log("Press Ctrl+C to quit.");
    });
}).catch(error => console.error("TypeORM connection error: ", error));

Current versions of cors and Node

cors: "^2.8.4"
Node: v8.4.0

The only change that recently done was on Friday when I included the following packages

multer: "^1.3.0"
@google-cloud/datastore: "^1.1.0"
@google-cloud/storage: "^1.4.0"

and everything was working till this morning, same version is deployed on gcloud and this works so I am a little bemused as to why I Am suddenly getting this error and what could be the cause.

Any help is greatly appreciated

like image 493
Neil Stevens Avatar asked Oct 27 '25 05:10

Neil Stevens


1 Answers

You have to have something such as

const cors = require('cors');

in the top of your file, and then refer to the module as cors, not Cors.

like image 89
Golo Roden Avatar answered Oct 28 '25 20:10

Golo Roden



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!