Sushant Paudel
Sushant Paudel

Reputation: 106

SyntaxError: Unexpected token = on module

I have been using fat arrow function inside classes in Nodejs and I have been getting the below error which is working fine on my PC.

static post = async (req, res, next) => {
              ^

SyntaxError: Unexpected token =
    at Module._compile (internal/modules/cjs/loader.js:723:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at Object.<anonymous> (/home/selacomn/repositories/ecommerce-backend/src/mobile/routes/order.js:2:25)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)

The environment I used in deployment is:

node --version >> v10.22.0
npm --version >> 6.14.6

This code is working fine on my system and the environment of my system is:

node --version >> v12.18.3
npm --version >> 6.14.6

I think that the versioning is not the problem, because I have encountered this problem previously but I forgot how did I do it. And, I cannot experiment on this development because the problem is within the server. So, Is there anything you guys could help on?

The code where problem arised is below:

class OrderController {
  static post = async (req, res, next) => {
    Order.create()
  };
  static getOne = async (req, res, next) => {
    Order.getOne(id) 
  };
  static getAll = async (req, res, next) => {
    Order.getAll()
  };
}

Upvotes: 0

Views: 2253

Answers (1)

D. Pardal
D. Pardal

Reputation: 6587

From MDN:

The static keyword defines a static method for a class.

You seem to be trying to set a static property to an arrow function, which would effectively create a static method, but that's invalid syntax. The correct syntax is:

class OrderController {
  static async post(req, res, next) {
    Order.create();
  }
  static async getOne(req, res, next) {
    Order.getOne(id);
  }
  static async getAll(req, res, next) {
    Order.getAll();
  }
}

If you really need arrow functions, use assignments, but usually there's no reason to do that:

class OrderController {
}
OrderController.post = async (req, res, next) => {
  Order.create();
};
OrderController.getOne = async (req, res, next) => {
  Order.getOne(id);
};
OrderController.getAll = async (req, res, next) => {
  Order.getAll();
};

Upvotes: 1

Related Questions