Git Product home page Git Product logo

http-server's Introduction

@adonisjs/http-server


gh-workflow-image npm-image license-image

Introduction

Implementation of HTTP server used by AdonisJS. The package ships with a powerful Router, Middleware pipeline, helpers to create plain and signed URL for registered routes and much more.

Official Documentation

The documentation is available on the AdonisJS website

Contributing

One of the primary goals of AdonisJS is to have a vibrant community of users and contributors who believes in the principles of the framework.

We encourage you to read the contribution guide before contributing to the framework.

Code of Conduct

In order to ensure that the AdonisJS community is welcoming to all, please review and abide by the Code of Conduct.

License

AdonisJS HTTP server is open-sourced software licensed under the MIT license.

http-server's People

Contributors

aikrom avatar danpospisil avatar dependabot-preview[bot] avatar dependabot[bot] avatar julien-r44 avatar leadcodedev avatar robinvw1 avatar romainlanz avatar snyk-bot avatar targos avatar thetutlage avatar tomgobich avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

http-server's Issues

Feature/Bug - where route does not regex correctly

I'm trying to do a dynamic based route where it is matching a nested directory. For example, I could have:

/export
/export/dir1
/export/dir1/dir2
/export/dir1/dir2/etc

All being matched by the same route controller. I'm trying to do it using:

Route.get("/export/:path?", "export.controller.index").where("path", ".*");

Similar to what laravel proposes if you need this:
https://laravel.com/docs/8.x/routing#parameters-encoded-forward-slashes

But the router match ignores it and doesn't find the route

Resource route renaming

Package version

image

Node.js and npm version

image

Sample Code (to reproduce the issue)

In routes file:

Route.resource('/uploadTutorials', 'UploadTutorialsController').as('uploadTutorials')

In view:

// Not worked
{{ route('uploadTutorials.index') }}

// Worked
{{ route('upload_tutorials.index') }}

List of routes:

image

Make Request method parseQueryString configurable

Prerequisites

Currently AdonisJS parses query strings in requests by default in @adonisjs/http-server/build/src/Request/index.js method parseQueryString using package qs:

parseQueryString() {
    if (this.parsedUrl.query) {
        this.updateQs(qs_1.default.parse(this.parsedUrl.query));
        this.originalRequestData = { ...this.requestData };
    }
}

But the parse method of qs here is not configurable at all, even though the package offers many options:

interface IParseOptions {
    comma?: boolean | undefined;
    delimiter?: string | RegExp | undefined;
    depth?: number | false | undefined;
    decoder?: ((str: string, defaultDecoder: defaultDecoder, charset: string, type: 'key' | 'value') => any) | undefined;
    arrayLimit?: number | undefined;
    parseArrays?: boolean | undefined;
    allowDots?: boolean | undefined;
    plainObjects?: boolean | undefined;
    allowPrototypes?: boolean | undefined;
    parameterLimit?: number | undefined;
    strictNullHandling?: boolean | undefined;
    ignoreQueryPrefix?: boolean | undefined;
    charset?: 'utf-8' | 'iso-8859-1' | undefined;
    charsetSentinel?: boolean | undefined;
    interpretNumericEntities?: boolean | undefined;
}

Why this feature is required (specific use-cases will be appreciated)?

My use case is to allow comma separated values for array so instead of unnecessary long query strings like:
someArray[]=1&someArray[]=2&someArray[]=3
I can just send
someArray=1,2,3

Have you tried any other work arounds?

My work around is this hack to override parseQueryString method in Request class using macro.
In my AppProvider.ts:

public async boot() {
    const Request = this.app.container.use('Adonis/Core/Request')

    Request.macro('parseQueryString', function () {
      if (this.parsedUrl.query) {
        this.updateQs(qs.parse(this.parsedUrl.query, { comma: true }))
        // @ts-ignore
        this.originalRequestData = { ...this.requestData }
      }
    })
  }

Solution

Add optional "queryString" object of type QueryStringConfig (this is already used in @adonisjs/bodyparser package) to RequestConfig (part of ServerConfig in config/app.ts).
and that could be used in relevant line of parseQueryString method:
this.updateQs(qs_1.default.parse(this.parsedUrl.query, this.config.queryString || {}));

makeUrl error in types

The makeUrl signature indicate that the second parameter can be a MakeUrlOptions :

public makeUrl(
  routeIdentifier: string,
  params?: any[] | MakeUrlOptions,
  options?: MakeUrlOptions
): string

But when passing a MakeUrlOptions as a second parameter:

router.makeUrl('/posts', { prefixUrl: '/api' })

it returns /posts when /api/posts is expected.

Package version

v5.2.1

Node.js and npm version

v15.11.0

Sample Code (to reproduce the issue)

router.makeUrl('/posts', { prefixUrl: '/api' }) // /posts

and

router.makeUrl('/posts', undefined, { prefixUrl: '/api' }) // /api/posts

Redirect with 4xx not working

Prerequisites

We do our best to reply to all the issues on time. If you will follow the given guidelines, the turn around time will be faster.

  • Lots of raised issues are directly not bugs but instead are design decisions taken by us.
  • Make use of our forum, or discord server, if you are not sure that you are reporting a bug.
  • Ensure the issue isn't already reported.
  • Ensure you are reporting the bug in the correct repo.

Delete the above section and the instructions in the sections below before submitting

Package version

5.5.7

Node.js and npm version

14.18.1

Sample Code (to reproduce the issue)

Route.get('/test', async ({ response }) => { return response.status(404).redirect().toPath('/path') })

Response: Redirecting to /path

BONUS (a sample repo to reproduce the issue)

Duplicate route name error when using `.resouce()` in `.group()` with `.prefix()`

Duplicate route name error when using .resouce() in .group() with .prefix()

It seems to be problem with .resource() only, since with everything else grouping and prefixing works perfectly fine

RouterException: E_DUPLICATE_ROUTE_NAME: Duplicate route name "foobar.index"

Package version

"@adonisjs/core": "^5.0.4-preview-rc-2.1",
// http-server version
"@adonisjs/http-server": "4.0.9"

Node.js and npm version

NPM: 6.14.11
NodeJS: v15.6.0

Sample Code (to reproduce the issue)

// routes.ts
import Route from '@ioc:Adonis/Core/Route'

Route.group(() => {
  Route.resource('foobar', 'FooBarController')
}).prefix('v1')

Route.group(() => {
  Route.resource('foobar', 'SomeOtherController')
}).prefix('v2')

BONUS (a sample repo to reproduce the issue)

Setting trustProxy in config/app.ts throws an error

As per the docs: https://docs.adonisjs.com/guides/request#trusted-proxy a valid setting for trustProxy is

{
  trustProxy: proxyAddr.compile(true)
}

However, this throws an error when the server restarts

UPDATE: config/app.ts
[ info ]  re-starting http server...

  TypeError 

 unsupported trust argument

 at Object.<anonymous> /home/adonis/Development/Node/_clients/xxx/backend/config/app.ts:81
  76|    |
  77|    | Define the proxy servers that AdonisJs must trust for reading `X-Forwarded`
  78|    | headers.
  79|    |
  80|    */
❯ 81|    trustProxy: proxyAddr.compile(true),
  82|  
  83|    /*
  84|    |--------------------------------------------------------------------------
  85|    | Generating Etag
  86|    |--------------------------------------------------------------------------

   1  Function.compile
     /home/adonis/Development/Node/_clients/xxx/backend/node_modules/.pnpm/[email protected]/node_modules/proxy-addr/index.js:96

   2  Module._compile
     /home/adonis/Development/Node/_clients/xxx/backend/node_modules/.pnpm/[email protected]/node_modules/pirates/lib/index.js:136

   3  Object.newLoader [as .ts]
     /home/adonis/Development/Node/_clients/xxx/backend/node_modules/.pnpm/[email protected]/node_modules/pirates/lib/index.js:141

[ warn ]  Underlying HTTP server died with "0 code"

Am I missing something?

Matchit as a NPM dependency instead of Git dependency

Package version

v4.0.8

Node.js and npm version

Node.js: v14.15.1
NPM: 6.14.8

Asking

Would it be possible to publish matchit to install it through NPM registry instead of Git?
NPM 6 doesn't seem to handle git dependencies consistently, especially regarding the lockfile.

Not terminating request with 304 HTTP status and JSON response body

Package version

Fresh yarn create adonis-ts-app ... install

"devDependencies": {
    "@adonisjs/assembler": "^3.0.0",
    "adonis-preset-ts": "^1.1.0",
    "pino-pretty": "^4.3.0",
    "typescript": "^4.0.5",
    "youch": "^2.1.1",
    "youch-terminal": "^1.0.1"
  },
  "dependencies": {
    "@adonisjs/core": "^5.0.4-preview-rc",
    "@adonisjs/repl": "^1.0.0",
    "proxy-addr": "^2.0.6",
    "reflect-metadata": "^0.1.13",
    "source-map-support": "^0.5.19"
  }

Node.js and npm version

Node v14.5.0
NPM v6.14.8
Yarn v1.22.10

Sample Code (to reproduce the issue)

In your routes.ts / Controller:

import Route from "@ioc:Adonis/Core/Route"

Route.get("/", async ({ response }) => {
    return response.status(304).send({
        status: "NOT_MODIFIED",
        whatever: "Body you want to send"
    })
})

Description

Like you pointed out in https://github.com/adonisjs/http-server/blob/develop/src/Response/index.ts#L202, a response with 304 HTTP status should not include a body. However if you pass something which is not a plain String or Buffer the Adonis HTTP server logs a The "chunk" argument must be of type string or an instance of Buffer. Received an instance of Object error. That's because ServerResponse.end(body) only supports sending a stringified or Buffer body. Also there's no response sent at all (causing the request to terminate after a timeout or being infinite).

I suggest just omitting the body for 304 responses.
If you want i'm gonna open a PR.

Cyrillic parameters

Why this feature is required (specific use-cases will be appreciated)?

Current version adonisJS not supported Cyrillic parameters

Example:
image

image

Users should use decodeURIComponent function for decode any Cyrillic symbols in url

Example:
image

image

You can do it by default and then everyone will be happy :D

Also we can create global middleware, where we can change params for always decoding it, if it is possible.

Add 'requestBody' to RequestContract interface ('@ioc:Adonis/Core/Request' typings)

Why this feature is required (specific use-cases will be appreciated)?

It's very convenient to use ES6's Object Destructuring in controllers:

...
  public async register({
    request: {
      requestBody: { username, password },
    },
    response,
  }: HttpContextContract) {
    await UserService.create({ username, password })

    response.status(204)
  }
...

Have you tried any other work arounds?

typings/Request.d.ts:

declare module '@ioc:Adonis/Core/Request' {
  export interface RequestContract {
    requestBody: Record<string, any>
  }
}

Are you willing to work on it with little guidance?

No

Redirect with 4xx not working

Prerequisites

We do our best to reply to all the issues on time. If you will follow the given guidelines, the turn around time will be faster.

  • Lots of raised issues are directly not bugs but instead are design decisions taken by us.
  • Make use of our forum, or discord server, if you are not sure that you are reporting a bug.
  • Ensure the issue isn't already reported.
  • Ensure you are reporting the bug in the correct repo.

Delete the above section and the instructions in the sections below before submitting

Package version

5.5.7

Node.js and npm version

14.18.1

Sample Code (to reproduce the issue)

response.status(404).redirect().toPath('/path')

BONUS (a sample repo to reproduce the issue)

Redirecting to /path

Improve `router.resource` type-checking

Package version

7.0.2

Describe the bug

Hello,

I noticed that router.resource does not give Typescript error when the given controller does not implement all the needed REST methods.

For example, the following code does not show any error but will fail at runtime:

import router from '@adonisjs/core/services/router'

class TestController {}

router.resource('test', TestController) // <- TS does not complain

The equivalent code using get, post, ... methods does show Typescript errors

import router from '@adonisjs/core/services/router'

class TestController {}

router.get('/test/create', [TestController, 'create'])  // <- TS complains
router.get('/test', [TestController, 'index'])  // <- TS complains
router.post('/test', [TestController, 'store'])  // <- TS complains
router.get('/test/:id', [TestController, 'show'])  // <- TS complains
router.get('/test/:id/edit', [TestController, 'edit'])  // <- TS complains
router.put('/test/:id', [TestController, 'update'])  // <- TS complains
router.patch('/test/:id', [TestController, 'update'])  // <- TS complains
router.delete('/test/:id', [TestController, 'destroy'])  // <- TS complains

A simple test for this would be:

test.group('Router | typechecking', () => {
  test('router.resource gives Typescript error when a RESTfull method is missing in the given controller', () => {
    class TestControllerClass {}
    const router = new RouterFactory().create()
    router.resource('test', TestControllerClass) // @ts-expect-error
  })
})

Can I make a PR to fix this?

Reproduction repo

No response

flushHeaders does not send headers over the network

Package version

@adonisjs/[email protected]

Node.js and npm version

[email protected], [email protected]

Sample Code (to reproduce the issue)

// In any controller
ctx.response.header('Content-Type', 'application/pdf');
ctx.response.flushHeaders(200);
// If I don't execute this line, the headers are not sent over the network
ctx.response.response.flushHeaders();

// ... do something async
ctx.response.response.end(data);

In adonis response, calling flushHeaders calls writeHead on the response stream

this.response.writeHead(statusCode || this.response.statusCode, this.headers)

But when calling writeHead, the headers actually get flushed only given this "except" condition:
https://github.com/nodejs/node/blob/ccf46ba0f5ce02ae85b8bdb5e29acfc376caf9fc/lib/_http_outgoing.js#L547

You are supposed to call flushHeaders on the response stream to start sending data over the network

Some context about why I'm using adonisjs in this weird way:

  • The controller is called when a user wants to download a file which is generated on the fly (doesn't exist on disk yet). The generation takes some time but I want the browser's file download UI to appear right away. Otherwise it might seem like the action is doing nothing.
  • The file does not exist yet, so I cannot use a stream to do that.

Disclaimer: I'm not familiar with how the node http library works so this is just my take and I might be wrong. However in a real adonis application I observed that flushHeaders did not actually send the headers which seems like a bug to me. Calling ctx.response.response.flushHeaders() fixed the issue.

HttpContext & Route.makeUrl Parse Two Different Param Names When File Extension Is Included

Came across a use-case via a GH Discussion where if there's a file extension added to the end of a route param name the HttpContext will exclude the file extension from the param name. However, the URL generator via Route.makeUrl includes the file extension in the param name.

Package version

@adonisjs/core: ^5.9.0
@adonisjs/repl: ^3.1.11
@adonisjs/session: ^6.4.0
@adonisjs/shield: ^7.1.0
@adonisjs/view: ^6.2.0

Node.js and npm version

Node: v16.13.0
NPM: v8.1.0

Sample Code (to reproduce the issue)

For the route definition GET: /test/:slug.html the HttpContext considers slug the param name whereas the URL generator via Route.makeUrl considers slug.html the param name

Route.get('/', async ({ response }) => {
  let failedUrl = ''

  try {
    // fails because it's expecting 'slug.html' as param name
    failedUrl = Route.makeUrl('test', { slug: 'somevalue' })
  } catch (error) {
    console.error({ error })
  }

  // works, but ends up excluding `.html` from final url output 
  // since it's considered a part of the param name
  const workingUrl1 = Route.makeUrl('test', { 'slug.html': 'somevalue' })
  const workingUrl2 = Route.makeUrl('test', ['somevalue'])

  return response.json({
    failedUrl,    // output: ""                 expected: "/test/somevalue.html"
    workingUrl1,  // output: "/test/somevalue"  expected: "/test/somevalue.html"
    workingUrl2   // output: "/test/somevalue"  expected: "/test/somevalue.html"
  })
})

Route.get('/test/:slug.html', async ({ response, params }) => {
  return response.json(params) // output: { slug: "somevalue" }  expected: { slug: "somevalue" }
}).as('test')

BONUS (a sample repo to reproduce the issue)

Here is a sample repo for the above example

Auth middleware not recognized and not working

I just installed the auth module using the api guard and redis for storage. When I try to add the middleware function to a route in routes.ts, VSCode give me an error about the types, and the middleware is not throwing error for unauthorized request. I added the auth middleware to registedNamed like in the example.

image

Package version

@adonisjs/core: 5.0.4-preview-rc
@adonisjs/auth: 5.1.1

Node.js and npm version

nodejs: v14.15.4
npm: 6.14.10
(yarn: 1.22.10)

Sample Code (to reproduce the issue)

// routes.ts
Route.resource('admins', 'AdminsController').apiOnly().middleware('auth')
// kernel.ts
Server.middleware.registerNamed({ auth: 'App/Middleware/Auth' })

BONUS (a sample repo to reproduce the issue)

Route.makeUrl doesn't seem to work

Package version

"@adonisjs/core": "^5.3.0",
"@adonisjs/repl": "^3.1.0",
"@adonisjs/assembler": "^5.0.0",
"adonis-preset-ts": "^2.1.0",

Node.js and npm version

node 14.15.1
npm 6.14.8

Sample Code (to reproduce the issue)

Create a route:

Route.get('/test', 'TestController.index').as('test')

Create a controller

import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'

export default class TestController {
  public async index({}: HttpContextContract) {
    return { hello: 'from TestController.index' }
  }
}

Try to call generate the url either using the controller method or name, as stated in the docs:

Route.makeUrl('test')
Route.makeUrl('TestController.index')

Both commands above fail with the following error:

IocLookupException: E_IOC_LOOKUP_FAILED: Cannot resolve "Adonis/Core/Route" namespace from the IoC Container

at /home/jesse/code/stocks/server-adonis/commands/TestCommand.ts(anonymous):1
1
2  import Route from '@ioc:Adonis/Core/Route'
3  import { BaseCommand } from '@adonisjs/core/build/standalone'
4
5  export default class TestCommand extends BaseCommand {
6    /**
7     * Command name is used to run the command

Consider changing type RequestContract.qs() from Record<string, any> to more strict type

Why this feature is required (specific use-cases will be appreciated)?

I happen to get and error where I accidentally use value with type of string in place where it needs number which I get value from RequestContract.qs(). It doesn't get detected because qs() has value type of any which always pass type check.

This is also quite misleading because qs() is always string or string[].

This also applied to params I think.

Rare case that might need to consider: If we just set return type to Record<string, string | string[] | undefined> it will break when we use updateQs() with we insert non string value, TypeScript still think it all string.

Have you tried any other work arounds?

I can override with
{ request: { qs: () => Record<string, string | string[] | undefined> } } & HttpContextContract

Are you willing to work on it with little guidance?

I don't have time to, sorry.

MakeUrl is deprecated

Package version

5.7.1

Node.js and npm version

14.15.5 and 7.23.0

Sample Code (to reproduce the issue)

Use a redirect().toRoute('YourController') in any application to print this message in the console

(node:30252) You are using legacy the API of the "Route.makeUrl". We recommend reading the docs and use the latest API: DeprecationWarning

This is created in this file and reading the doc, the new url builder must be used

Redirection Issues with resource routes being non standard

Issue

The issue is probably with the router since it seems to be trying to send the user back to the show method which isn't registered in the resource and added in except.

So, with the code example attached below, the expected flow is like so
profile.index is rendered => User modifies data => profile.update is called with the new data => User is redirected to profile.index and the new data is visible.

With the current flow, the first part works as updated but it redirects back to profile/:id instead.

I do have turbolinks in the app.

If turbolinks in enabled on the form (default behaviour)

  • the update goes through but redirection fails as it redirects back to the PUT request on the /profile url

If turbolinks is disabled on this one form

  • the redirections fail altogether

If turbolinks is not a part of the bundle

  • the redirections and form submission fail as well

Package version

"@adonisjs/auth": "^8.2.3",
"@adonisjs/core": "^5.8.0",
"@adonisjs/lucid": "^18.3.0",
"@adonisjs/repl": "^3.1.0",
"@adonisjs/session": "^6.2.0",
"@adonisjs/shield": "^7.0.0",
"@adonisjs/view": "^6.1.0",

Node.js and npm version

node - v18.16.0
npm - 9.5.1

Sample Code (to reproduce the issue)

export default class ProfilesController { 
	public async index({ view, response, auth }: HttpContextContract) {
	    const userDetails = await User.find(auth.user!.id)
	    return view.render('profiles/index', {
	      user: userDetails.serialize(),
		})
	}

	  public async update({
	    request,
	    response,
	    session,
	    auth,
	  }: HttpContextContract) {
	    const user = await User.find(auth.user!.id)
	    // modify users
	    await user!.save()
	    session.flash('message', 'Updated Profile')
	    return response.redirect().toRoute('ProfilesController.index')
	  }
 }

BONUS (a sample repo to reproduce the issue)

https://github.com/barelyhuman/resource-redir-adonis-issue

Route Identifier on Subdomain

Prerequisites

Identifier name is not working in subdomain without prefix, any solution?

Package.json

{
  "name": "example.com",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev": "node ace serve --watch",
    "build": "node ace build --production",
    "start": "node server.js",
    "test": "node ace test",
    "lint": "eslint . --ext=.ts",
    "format": "prettier --write ."
  },
  "eslintConfig": {
    "extends": [
      "plugin:adonis/typescriptApp",
      "prettier"
    ],
    "plugins": [
      "prettier"
    ],
    "rules": {
      "prettier/prettier": [
        "error"
      ]
    }
  },
  "eslintIgnore": [
    "build"
  ],
  "prettier": {
    "trailingComma": "es5",
    "semi": false,
    "singleQuote": true,
    "useTabs": false,
    "quoteProps": "consistent",
    "bracketSpacing": true,
    "arrowParens": "always",
    "printWidth": 100
  },
  "devDependencies": {
    "@adonisjs/assembler": "^5.9.5",
    "@babel/core": "^7.17.0",
    "@babel/preset-env": "^7.16.0",
    "@japa/preset-adonis": "^1.2.0",
    "@japa/runner": "^2.5.1",
    "@symfony/webpack-encore": "4.1.1",
    "@types/proxy-addr": "^2.0.0",
    "@types/source-map-support": "^0.5.6",
    "adonis-preset-ts": "^2.1.0",
    "autoprefixer": "^10.4.14",
    "eslint": "^8.39.0",
    "eslint-config-prettier": "^8.8.0",
    "eslint-plugin-adonis": "^2.1.1",
    "eslint-plugin-prettier": "^4.2.1",
    "pino-pretty": "^10.0.0",
    "postcss": "^8.4.23",
    "postcss-loader": "^7.3.0",
    "prettier": "^2.8.8",
    "tailwindcss": "^3.3.2",
    "typescript": "~4.6",
    "webpack": "^5.72",
    "webpack-cli": "^4.9.1",
    "youch": "^3.2.3",
    "youch-terminal": "^2.2.0"
  },
  "dependencies": {
    "@adonisjs/ally": "^4.1.5",
    "@adonisjs/auth": "^8.2.3",
    "@adonisjs/core": "^5.8.0",
    "@adonisjs/lucid": "^18.3.0",
    "@adonisjs/repl": "^3.1.0",
    "@adonisjs/session": "^6.2.0",
    "@adonisjs/shield": "^7.0.0",
    "@adonisjs/view": "^6.1.0",
    "luxon": "^3.3.0",
    "mysql2": "^3.2.4",
    "proxy-addr": "^2.0.7",
    "reflect-metadata": "^0.1.13",
    "source-map-support": "^0.5.21"
  }
}

Node.js and npm version

node.js: v19.8.1
npm: 9.5.1

routes.ts

Route.group(() => {
  Route.get('/', 'IndexController.index').as('member.index')
  Route.get('/login', 'IndexController.login').as('member.login')

  Route.group(() => {
    Route.post('login', 'AuthController.login')
    Route.post('facebook', 'AuthController.facebook')
    Route.post('google', 'AuthController.google')
  }).prefix('auth')

  Route.group(() => {
    Route.get('dashboard', 'DashboardController.index').as('member.dashboard')
  }).middleware('auth')
})
  .namespace('App/Controllers/Http/Member')
  .domain(':admin.example.com')

IndexController.ts

export default class IndexController {
  public async index({ response, auth }: HttpContextContract) {
    auth.isAuthenticated
      ? response.redirect().toRoute('member.dashboard')
      : response.redirect().toRoute('member.login')
  }

  public async login({ view }: HttpContextContract) {
    view.render('member::login')
  }
}

Route List

GET|HEAD    /uploads/* ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── drive.local.serve β€Ί Closure
GET|HEAD    / ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── Closure
GET|HEAD    :admin.example.com/ ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── member.index β€Ί Member/IndexController.index
GET|HEAD    :admin.example.com/login ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── member.login β€Ί Member/IndexController.login
POST        :admin.example.com/auth/login ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── Member/AuthController.login
POST        :admin.example.com/auth/facebook ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── Member/AuthController.facebook
POST        :admin.example.com/auth/google ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── Member/AuthController.google
GET|HEAD    :admin.example.com/dashboard ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── member.dashboard β€Ί Member/DashboardController.index

ERROR

RouterException
E_CANNOT_FIND_ROUTE: Cannot find route for "member.login" identifier

Handler Custom 404 page error

Package version

Adonisjs 5
@adonisjs/core@^5.0.0-preview-rc
@adonisjs/http-server@^3.0.1

Node.js and npm version

Node.js: v14.8.0
npm: v6.14.7

Sample Code (to reproduce the issue)

Exceptions/Handler.ts

import Logger from '@ioc:Adonis/Core/Logger'
import HttpExceptionHandler from '@ioc:Adonis/Core/HttpExceptionHandler'

export default class ExceptionHandler extends HttpExceptionHandler {

        protected disableStatusPagesInDevelopment = false
	protected statusPages = {
		'404': 'errors.not-found',
		'500..599': 'errors.server-error',
	}

	constructor () {
		super(Logger)
	}
}

Server errors correctly display the custom error page.
404 errors only display an error message:

E_ROUTE_NOT_FOUND: Cannot GET: /test

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.