3

I want to create a custom api in strapi backend for that i generated a plugin which will help me to create a api for me ...so i created a plugin called test for testing purpose,when i try to access the test response in postman its showing 404 error is not accessible ...

i will show you the code

This is my route file..

src/plugins/test/server/routes

export default [
   {
      method: 'GET',
      path: '/',
      handler: 'myController.index',
      config: {
         policies: [],
         auth:false
      },
   },

];

This is my controller file..

src/plugins/test/server/controllers/my-controller.ts

import { Strapi } from '@strapi/strapi';

export default ({ strapi }: { strapi: Strapi }) => ({
  index(ctx) {
    ctx.body = strapi
      .plugin('test')
      .service('myService')
      .getWelcomeMessage();
  },
});

This is my service file..

src/plugins/test/server/services/my-service.ts

import { Strapi } from '@strapi/strapi';

export default ({ strapi }: { strapi: Strapi }) => ({
  getWelcomeMessage() {
    return 'Welcome to Strapi ';
  },
});

above code is by default generated by the strapi plugin ..when i m trying to access via endpoint http://localhost:1337/test is not getting response back why is the issue please help me identify the issue..

t3__rry
  • 2,817
  • 2
  • 23
  • 38
yash singh
  • 31
  • 3

3 Answers3

0

You need to define the route's prefix and controller properties.

src/plugins/test/server/routes/index.js

export default {
  routes: [
    {
      method: 'GET',
      path: '/',
      handler: 'myController.index',
      config: {
        policies: [],
        auth: false,
      },
    },
  ],
  prefix: '/test',
  controller: 'my-controller',
};

Make sure to restart your Strapi server after making these changes

lopm46
  • 470
  • 2
  • 7
0

I think you may need to update the routes file. You have set the route path to '/', which means that you can access this endpoint through http://localhost:1337/, not through http://localhost:1337/test. It may work if you just change the path in the routes file as the following.

export default [
   {
      method: 'GET',
      path: '/test',
      handler: 'myController.index',
      config: {
         policies: [],
         auth:false
      },
   },
];
Arrow
  • 532
  • 5
  • 18
0

You are missing a part. Strapi is not that smart to find your routes.js file.

What you have to do is to create a file in your plugin directory, like so: plugins/my-plugin/strapi-server.js

inside if it, you should export a function as default and return the configurations of the plugin:

strapi-server.js
module.exports = () => {
    return {
        controllers: [
            ...
        ],
        routes: [
            {
              method: 'GET',
              path: '/',
              handler: 'myController.index',
              config: {
                  policies: [],
                  auth:false
              },  
            }
        ]
    }
}