Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to register plugin #379

Closed
2 tasks done
mage1k99 opened this issue Aug 8, 2022 · 6 comments
Closed
2 tasks done

Unable to register plugin #379

mage1k99 opened this issue Aug 8, 2022 · 6 comments

Comments

@mage1k99
Copy link

mage1k99 commented Aug 8, 2022

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.4.0

Plugin version

4.1.0

Node.js version

v16.16.0

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

12.5 (21G72) on M1

Description

I have created project using fastify-cli. I'm trying to add @fastify/multipart plugin but the support for multipart is not added. I searched for similar issues too. I found none of them worked for me

Plugins used

  • @fastify/autoload
  • @fastify/cookie
  • @fastify/cors
  • @fastify/jwt
  • @fastify/multipart
  • @fastify/session
  • @fastify/view
  • @fastify/sensible

Methods I tried

fastify.addContentTypeParser(
    "multipart/form-data",
    (request, _payload, done) => {
      done(null, request);
    }
  );

It returns true but still throws 415 : Content type not supported. I'll post the chunks of the code I've used

Steps to Reproduce

app.ts

import { join } from "path";
import AutoLoad, {
  AutoloadPluginOptions,
} from "@fastify/autoload";
import { FastifyPluginAsync } from "fastify";
import { connect } from "mongoose";

export type AppOptions = {
  // Place your custom options for app below here.
} & Partial<AutoloadPluginOptions>;

const app: FastifyPluginAsync<AppOptions> = async (
  fastify,
  opts
): Promise<void> => {
  connect(process.env.MONGODB_URI || "")
    .then(() => {
      fastify.log.info("Connected with database");
    })
    .catch((error) => {
      fastify.log.error(
        "Unable to connect with database ->",
        error
      );
      process.exit(1);
    });

  // Do not touch the following lines

  // This loads all plugins defined in plugins
  // those should be support plugins that are reused
  // through your application
  void fastify.register(AutoLoad, {
    dir: join(__dirname, "plugins"),
    options: opts,
  });

  fastify.addContentTypeParser(
    "multipart/form-data",
    (request, _payload, done) => {
      done(null, request);
    }
  );

  console.log(
    "has content parser type multipart",
    fastify.hasContentTypeParser("multipart/form-data")
  );

  // This loads all plugins defined in routes
  // define your routes in one of these
  void fastify.register(AutoLoad, {
    dir: join(__dirname, "routes"),
    options: opts,
  });
};

export default app;
export { app };

plugins/global.ts

here i store the plugins like multipart/form-data to be registered

// loads global plugins for fastify
// incl. cors, multipart file upload plugin

import fp from "fastify-plugin";
import { FastifyCorsOptions } from "@fastify/cors";
import { PointOfViewOptions } from "@fastify/view";
import session from "@fastify/session";
import { FastifyMultipartOptions } from "@fastify/multipart";

export default fp(async (fastify, opts) => {
  fastify.register<FastifyMultipartOptions>(
    require("@fastify/multipart"),
    {
      addToBody: true,
    }
  );
  fastify.register<FastifyCorsOptions>(
    require("@fastify/cors"),
    {
      origin: [
        /localhost:8080/,
        /localhost:8081/,
        /app.jeevantrust.org/,
      ],
      credentials: true,
    }
  );
  fastify.register<PointOfViewOptions>(
    require("@fastify/view"),
    {
      engine: {
        handlebars: require("handlebars"),
      },
    }
  );
  fastify.register<session.Options>(
    require("@fastify/session"),
    {
      secret: process.env.SESSION_KEY || "",
    }
  );
});

Routes for multipart

import activateAccountController from "../controllers/pages/activate_account_controller";

const staticRoutes = async (
  fastify: any,
  _opts: any
): Promise<void> => {
  fastify.post(
    "/account/activate",
    activateAccountController.startActivateProcess
  );
};

export default staticRoutes;

activate_account_controller.ts

const startActivateProcess = async (
  request: FastifyRequestExtended,
  reply: FastifyReplyExtended
) => {
  console.log("hii");
  const fields = request.body;
  return reply.send(fields);
};
export default {
  startActivateProcess,
};

Output produced by postman

{
    "statusCode": 415,
    "code": "FST_ERR_CTP_INVALID_MEDIA_TYPE",
    "error": "Unsupported Media Type",
    "message": "Unsupported Media Type: multipart/form-data; boundary=--------------------------837419173164089124228911"
}

The output showed via cURL

curl --location --request POST 'localhost:25411/accounts/activate' \
--form 'password="password"' \
--form 'repeat_password="password"'
{"statusCode":415,"code":"FST_ERR_CTP_INVALID_MEDIA_TYPE","error":"Unsupported Media Type","message":"Unsupported Media Type: multipart/form-data; boundary=------------------------88c1c765446a12db"}%  

The log shown during request

[App] [1659979595467] INFO (50629 on mac-mini.local): Unsupported Media Type: multipart/form-data; boundary=------------------------88c1c765446a12db
[App]     reqId: "req-1"
[App]     res: {
[App]       "statusCode": 415
[App]     }
[App]     err: {
[App]       "type": "FastifyError",
[App]       "message": "Unsupported Media Type: multipart/form-data; boundary=------------------------88c1c765446a12db",
[App]       "stack":
[App]           FastifyError: Unsupported Media Type: multipart/form-data; boundary=------------------------88c1c765446a12db
[App]               at ContentTypeParser.run (/Users/mage1k99/Documents/Fossfreaks/API/expense-api/node_modules/fastify/lib/contentTypeParser.js:152:16)
[App]               at handleRequest (/Users/mage1k99/Documents/Fossfreaks/API/expense-api/node_modules/fastify/lib/handleRequest.js:39:39)
[App]               at runPreParsing (/Users/mage1k99/Documents/Fossfreaks/API/expense-api/node_modules/fastify/lib/route.js:489:5)
[App]               at Object.routeHandler [as handler] (/Users/mage1k99/Documents/Fossfreaks/API/expense-api/node_modules/fastify/lib/route.js:436:7)
[App]               at Router.lookup (/Users/mage1k99/Documents/Fossfreaks/API/expense-api/node_modules/find-my-way/index.js:368:14)
[App]               at Router.defaultRoute (/Users/mage1k99/Documents/Fossfreaks/API/expense-api/node_modules/fastify/fastify.js:640:23)
[App]               at Router._defaultRoute (/Users/mage1k99/Documents/Fossfreaks/API/expense-api/node_modules/find-my-way/index.js:511:14)
[App]               at Router.lookup (/Users/mage1k99/Documents/Fossfreaks/API/expense-api/node_modules/find-my-way/index.js:366:36)
[App]               at Server.emit (node:events:527:28)
[App]               at parserOnIncoming (node:_http_server:956:12)
[App]       "name": "FastifyError",
[App]       "code": "FST_ERR_CTP_INVALID_MEDIA_TYPE",
[App]       "statusCode": 415
[App]     }
[App] [1659979595470] INFO (50629 on mac-mini.local): request completed
[App]     reqId: "req-1"
[App]     res: {
[App]       "statusCode": 415
[App]     }
[App]     responseTime: 3.443291999399662

Expected Behavior

Expect fastify to register the plugin and work

@mcollina
Copy link
Member

mcollina commented Aug 9, 2022

Thanks for reporting!

Can you provide steps to reproduce? We often need a reproducible example, e.g. some code that allows someone else to recreate your problem by just copying and pasting it. If it involves more than a couple of different file, create a new repository on GitHub and add a link to that.

@mage1k99
Copy link
Author

mage1k99 commented Aug 9, 2022

Sorry for delay, I was reproducing the error and the it was working fine. I don't know what caused it or anything. I re-initialized the whole project and its working good.

@mage1k99 mage1k99 closed this as completed Aug 9, 2022
@mage1k99
Copy link
Author

Found another reason for 415

  • If you send a form-data request with a route that is not present/ registered, then instead of showing 404 it shows 415
{
    "statusCode": 415,
    "code": "FST_ERR_CTP_INVALID_MEDIA_TYPE",
    "error": "Unsupported Media Type",
    "message": "Unsupported Media Type: multipart/form-data; boundary=--------------------------028351211695914856584111"
}

@Eomm
Copy link
Member

Eomm commented Aug 16, 2022

Please open a new detailed issue adding a Minimal, Reproducible Example.

@mage1k99
Copy link
Author

Shall I create another issue to report this ? or continue in this thread itself ?

@Eomm
Copy link
Member

Eomm commented Aug 17, 2022

a new detailed issue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants