我最近開始在adonisjs框架上開發應用程序。我可以選擇使用expressjs,但我更喜歡adonisjs,因爲我喜歡它的結構(主要是laravel風格)。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
配置/ 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服務(使用郵遞員)。它驗證用戶,但在const token = request.auth.generate(user)
處拋出異常,並說request.auth.generate is not a function
。
我不知道發生了什麼事情。請幫忙。
感謝
你使用的是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
我有''版本「:」3.2.1「' – Ali