私は最近、adonisjsフレームワークでアプリケーションの開発を開始しました。私はexpressjを使用するオプションがありましたが、私はそれが構造化された方法(主にララベルスタイル)を愛するので、私は好きです。Adonis.js RESTFUL API回避策
現在、RESTFUL APIを構築しようとしていますが、基本的なルーティング/ミドルウェア/ apiController(すべてのapiリクエストを処理するカスタムコントローラ)のシナリオを理解できません。
routes.js
Route.post('api/v1/login', 'ApiController.login')
Route.post('api/v1/register', 'ApiController.register')
// API Routes
Route.group('api', function() {
Route.get('users', 'ApiController.getUsers')
}).prefix('/api/v1').middlewares(['auth:api'])
ApiController.js
'use strict'
const User = use('App/Model/User')
const Validator = use('Validator')
const FAIL = 0
const SUCCESS = 1
class ApiController {
* login (request, response) {
let jsonResponse = {}
const email = request.input('email')
const password = request.input('password')
// validate form input
const rules = {
email: 'required|email',
password: 'required'
}
const messages = {
'email.required': 'Email field is required.',
'password.required': 'Password field is required.'
}
const validation = yield Validator.validateAll(request.all(), rules, messages)
if (validation.fails()) {
jsonResponse.status = FAIL
jsonResponse.response = {}
jsonResponse.response.message = validation.messages()[0].message
} else {
try {
yield request.auth.attempt(email, password)
const user = yield User.findBy('email', email)
const token = yield request.auth.generate(user)
jsonResponse.status = SUCCESS
jsonResponse.response = {}
jsonResponse.response.message = "Logged In Successfully"
jsonResponse.response.user = user
jsonResponse.response.token = token
} catch (e) {
jsonResponse.status = FAIL
jsonResponse.response = {}
jsonResponse.response.message = e.message
}
}
return response.json(jsonResponse)
}
}
module.exports = ApiController
のconfig/auth.js
'use strict'
const Config = use('Config')
module.exports = {
/*
|--------------------------------------------------------------------------
| Authenticator
|--------------------------------------------------------------------------
|
| Authenticator is a combination of HTTP Authentication scheme and the
| serializer to be used for retrieving users. Below is the default
| authenticator to be used for every request.
|
| Available Schemes - basic, session, jwt, api
| Available Serializers - Lucid, Database
|
*/
authenticator: 'session',
/*
|--------------------------------------------------------------------------
| Session Authenticator
|--------------------------------------------------------------------------
|
| Session authenticator will make use of sessions to maintain the login
| state for a given user.
|
*/
session: {
serializer: 'Lucid',
model: 'App/Model/User',
scheme: 'session',
uid: 'email',
password: 'password'
},
/*
|--------------------------------------------------------------------------
| Basic Auth Authenticator
|--------------------------------------------------------------------------
|
| Basic Authentication works on Http Basic auth header.
|
*/
basic: {
serializer: 'Lucid',
model: 'App/Model/User',
scheme: 'basic',
uid: 'email',
password: 'password'
},
/*
|--------------------------------------------------------------------------
| JWT Authenticator
|--------------------------------------------------------------------------
|
| Jwt authentication works with a payload sent with every request under
| Http Authorization header.
|
*/
jwt: {
serializer: 'Lucid',
model: 'App/Model/User',
scheme: 'jwt',
uid: 'email',
password: 'password',
secret: Config.get('app.appKey')
},
/*
|--------------------------------------------------------------------------
| API Authenticator
|--------------------------------------------------------------------------
|
| Api authenticator authenticates are requests based on Authorization
| header.
|
| Make sure to define relationships on User and Token model as defined
| in documentation
|
*/
api: {
serializer: 'Lucid',
model: 'App/Model/Token',
scheme: 'api'
}
}
設定を:ここで
は、私がこれまで行ってきたものです/shield.js
'use strict'
module.exports = {
/*
|--------------------------------------------------------------------------
| Content Security Policy
|--------------------------------------------------------------------------
|
| Content security policy filters out the origins not allowed to execute
| and load resources like scripts, styles and fonts. There are wide
| variety of options to choose from.
| @examples
| directives: {
| defaultSrc: ['self', '@nonce', 'cdnjs.cloudflare.com']
| }
*/
csp: {
directives: {
},
reportOnly: false,
setAllHeaders: false,
disableAndroid: true
},
/*
|--------------------------------------------------------------------------
| X-XSS-Protection
|--------------------------------------------------------------------------
|
| X-XSS Protection saves from applications from XSS attacks. It is adopted
| by IE and later followed by some other browsers.
|
*/
xss: {
enabled: true,
enableOnOldIE: false
},
/*
|--------------------------------------------------------------------------
| Iframe Options
|--------------------------------------------------------------------------
|
| xframe defines whether or not your website can be embedded inside an
| iframe. Choose from one of the following options.
| @available options
| DENY, SAMEORIGIN, ALLOW-FROM http://example.com
*/
xframe: 'DENY',
/*
|--------------------------------------------------------------------------
| No Sniff
|--------------------------------------------------------------------------
|
| Browsers have a habit of sniffing content-type of a response. Which means
| files with .txt extension containing Javascript code will be executed as
| Javascript. You can disable this behavior by setting nosniff to false.
|
*/
nosniff: true,
/*
|--------------------------------------------------------------------------
| No Open
|--------------------------------------------------------------------------
|
| IE users can execute webpages in the context of your website, which is
| a serious security risk. Below options will manage this for you.
|
*/
noopen: true,
/*
|--------------------------------------------------------------------------
| CSRF Protection
|--------------------------------------------------------------------------
|
| CSRF Protection adds another layer of security by making sure, actionable
| routes does have a valid token to execute an action.
|
*/
csrf: {
enable: true,
methods: ['POST', 'PUT', 'DELETE'],
filterUris: ['/api/v1/login', '/api/v1/register'],
compareHostAndOrigin: true
}
}
私はログインWebサービス(postmanを使用)を押しました。ユーザーを検証しますが、const token = request.auth.generate(user)
に例外がスローされ、request.auth.generate is not a function
と表示されます。
私は何が起こっているのか分かりません。助けてください。あなたが使用して(JWTトークンを生成する(ユーザーがログインAPIコールを呼び出したとき)およびログインサービスを要求したアプリは、それを保存し、将来の要求を作ってそれを使用できるように、それを返送する必要が
おかげ
3.2または4.0を使用していますか?新しいプロジェクトなら4.0(ndlr:http://dev.adonisjs.com/)に切り替えることをお勧めします。 –
私はちょうど 'adonis --version'をしてくれました。それは私に2.1.9を与えました。どのように私はadonisjsを更新できますか?私は公式の文書http://adonisjs.com/docs/3.2/installationに記述されているように、まったく同じ手順でインストールしました。 'package.json'の – Ali
私は '' version ":" 3.2.1 "' – Ali