최근 adonisjs 프레임 워크에서 응용 프로그램을 개발하기 시작했습니다. 나는 익스프레션을 사용할 수있는 선택권이 있었지만 구조화 된 방식 (주로 라우트 스타일)을 좋아하기 때문에 선호했다.Adonis.js RESTFUL API 해결 방법
현재 RESTFUL API를 구축하고 있지만 기본 라우팅/미들웨어/apiController (모든 API 요청을 처리 할 사용자 정의 컨트롤러) 시나리오를 파악할 수 없습니다.
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'
}
}
설정을
routes.js : 여기
내가 지금까지 한 일이다 /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
}
}
이제 로그인 웹 서비스 (우편 배달부 사용)를 누릅니다. 사용자의 유효성을 검사하지만 const token = request.auth.generate(user)
에 예외가 발생하고 request.auth.generate is not a function
이라고 표시됩니다.
나는 무슨 일이 일어나고 있는지 모른다. 도와주세요.
감사
하고 저장 한 후 나중에 요청을하는 데 사용할 수있는 로그인 서비스를 요청한 응용 프로그램은 (사용 있도록 (사용자가 로그인 API 호출을 호출 할 때)는 JWT 토큰을 생성하고 다시 보낼 필요가
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