javascript - 运行示例代码时出错 - 导出类中的类 - 使用 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)
什么是正确的语法?
解决方案
实例类字段仅在使用标志的节点 >= 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来编译你的代码。
推荐阅读
- ruby-on-rails - rails 和 pg gem 的架构问题
- windows - 在 Golang 中创建 FILE_ID_DESCRIPTOR
- hyperledger-fabric - 测试调用另一个链码的 GoLang Invoke 方法
- android - om.google.android.material.textfield.TextInputLayout 浮动在 EditText 的左侧可绘制对象上方
- c# - 使用数组中的现有元素向类中的变量声明值(按从上到下的顺序)
- android - 为什么在 Looper 主线程中运行 Handler
- java - 运行时类型擦除验证
- android - 视图内的 RecyclerView 页面指示器
- javascript - 将数据从 Chrome 扩展弹出窗口保存到速率受限的后端
- javascript - change() 不是函数