Neil Stevens
Neil Stevens

Reputation: 3914

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

Upvotes: 4

Views: 10103

Answers (3)

Vijay Palaskar
Vijay Palaskar

Reputation: 536

You can read Express's cors documentation to learn more.

To apply cors to all routes in your project you can write:

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

Upvotes: 4

Neil Stevens
Neil Stevens

Reputation: 3914

Ok, so I found the problem which turned out to be PEBKAC.

While implementing file uploads and storage in gcloud, I had to enable CORS on gcloud and had saved the settings file in the root of my project, this file was called cors.json.

In the code posted in my question above the import statement was reading my cors.json file and not (as I thought) the cors NPM package.

Lesson learnt from this one should anyone else make the same rookie mistake I just made is be careful what you name your files and where you put them!!!

Upvotes: 0

Golo Roden
Golo Roden

Reputation: 150902

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.

Upvotes: 4

Related Questions