首页 > 解决方案 > 运行示例代码时出错 - 导出类中的类 - 使用 React Node.js 的 Auth0

问题描述

我正在尝试在我的 React 项目中运行用于创建身份验证服务的教程代码。

这是他们希望我运行的代码示例:

// src/Auth/Auth.js

import auth0 from 'auth0-js';

export default class Auth {
  auth0 = new auth0.WebAuth({
    domain:'domain.auth0.com',
    clientID: 'clientId',
    redirectUri: 'http://localhost:3000/callback',
    audience: 'https://myproject.auth0.com/userinfo',
    responseType: 'token id_token',
    scope: 'openid'
  });

  login() {
    this.auth0.authorize();
  }
}

当我运行它时,它会引发有关“导入”和“导出”关键字的错误。所以我把它改成这样:

const auth0 = require("auth0-js");

class Auth {
    auth = new auth0.WebAuth({
        domain: 'mydomain.auth0.com',
        clientID: 'clientID',
        redirectUri: 'http://localhost:3000/callback',
        audience: 'https://myproject.auth0.com/userinfo',
        responseType: 'token id_token',
        scope: 'openid'
  });

  login() {
    this.auth.authorize();
  }
}

module.exports = Auth;

但这给了我这个错误:

/Users/myname/my project/app/services/auth.js:4
    auth = new auth0.WebAuth({
         ^


SyntaxError: Unexpected token =
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:616:28)

什么是正确的语法?

标签: javascriptnode.jsexpressauth0

解决方案


实例类字段仅在使用标志的节点 >= 10 中受支持。--harmony

您可以改用getter,它在没有任何标志的情况下受支持。

class Auth {

    get auth() {
        if(!this._auth) {
            this._auth = new auth0.WebAuth({ /* ... */ });
        }

        return this._auth;
    }

    login() {
        this.auth.authorize();
    }
}

或者只是将其设置在constructor

class Auth {

    constructor() {

        this.auth = new Auth0.WebAuth({ /* ... */ });
    }
}

或者你可以使用babel来编译你的代码。


推荐阅读