Exporting routes in Koa - javascript

I'm having a strange issue when exporting my routes. For some reason, this code works for me:
app.js
import Koa from 'koa'
import routes from './routes/index'
const app = new Koa()
app.use(routes)
app.listen(3000, () => {
console.log('Server listening at http://localhost:3000')
})
export default app
routes/index.js
import Router from 'koa-router'
const router = new Router()
router.get('/', async ctx => {
await ctx.render('index')
})
export default router.routes()
but when I just export the routes function and then try to call it in app.js, I get an error:
app.js
import Koa from 'koa'
import routes from './routes/index'
const app = new Koa()
app.use(routes())
app.listen(3000, () => {
console.log('Server listening at http://localhost:3000')
})
export default app
routes/index.js
import Router from 'koa-router'
const router = new Router()
router.get('/', async ctx => {
await ctx.render('index')
})
export default router.routes
Why doesn't it work when I do it the second way?

You probably would like to export a bound function, so this inside it would refer to a router object.
It could be done nicely with a bind operator. I believe it's already available since you are using async/await.
import Router from 'koa-router'
const router = new Router()
router.get('/', async ctx => {
await ctx.render('index')
})
export default ::router.routes

You have to add a method:
router.allowedMethods()
like this:
app.use(router.routes(), router.allowedMethods())

Related

Why does export const work but export function does not?

I am trying to ensure that the same instance of vue-router is available in multiple places in my app.
The vue.router.js file exports the router like this:
export function createVueRouter() {
return createRouter({
history: createWebHistory('/')
routes: [//array of routes]
});
}
In my main app.js file (or main.js if you prefer) it is used like this:
import {createVueRouter} from './router/vue/vue.router.js';
const router = createVueRouter();
app.use(router);
The Vue app now has access to the vue-router. I now want the same vue-router to be available in an independent JS file. But the following does not work:
resusable.js
import {createVueRouter} from './router/vue/vue.router.js';
const router = createVueRouter();
//....
if (isLoggedInBasic !== true) {
return await router.push({name: "Signin"})
}
It creates a new instance of the vue-router and the router.push does not take the user to the Signin route (but the URL in the address bar does change).
If I change vue.router.js export to the following, it works fine all the files with the same router instance being shared between them.
export const VueRouter = createRouter({
history: createWebHistory('/')
routes: [//array of routes]
})
I cannot understand what is the difference and why it works when export const is used rather than just export function ()

Import Routes from routes.js is crashing my nodemon server

while importing Routes from routes.js nodemon crash is there any new update regarding the importation of Routes from routes.js??
Index.js code
import express from "express";
//components
import Connection from "./database/db.js";
import Routes from "./routes/Route.js";
const app = express();
app.use("/", Routes);
const PORT = 8000;
Connection();
app.listen(PORT, () =>
console.log(`Server is running successfully on PORT ${PORT}`)
);
Routes.js code
import express from "express";
import {
newConversation,
getConversation,
} from "../controller/conversation-controller.js";
import { addUser, getUser } from "../controller/user-controller.js";
import { newMessage, getMessage } from "../controller/message-controller.js";
const route = express.Router();
route.post("/add", addUser);
route.get("/users", getUser);
route.post("/conversation/add", newConversation);
route.post("/conversation/get", getConversation);
route.post("/message/add", newMessage);
route.get("/message/get/:id", getMessage);
export default route;

Cannot import a function in another file (node.js)

I have an issue that I can't resolve. I'm working with node.js and I simply want to use an export router function in another file .
Here is the code from the import file:
import express from "express";
import * as zoneInstance from "../../controllers/objectInstance/zoneInstance.js";
import { mobilityRouter } from "../../controllers/routerFunction/routerLogic.js";
const router = express.Router();
/* Router for mobility render
// const mobilityRouter = (zone, instance) => {
// return (
// router.get("/mobility/" + zone, instance)
// );
// } */
mobilityRouter(zoneInstance.shoulder.zone, zoneInstance.shoulder.mobilityRender());
Here is the code from the export file:
import express from "express";
const router = express.Router();
// Router for mobility render
export const mobilityRouter = (zone, instance) => {
return (
router.get("/mobility/" + zone, instance)
);
}
// Router for reinforcement render
export const reinforcementRouter = (zone, instance) => {
return (
router.get("/reinforcement/" + zone, instance)
);
}
// Router for proprioception
export const proprioceptionRouter = (zone, instance) => {
return (
router.get("/proprioception/" + zone, instance)
);
}
In the index.js
// Routes for
import mobilityRouter from "./routes/mobility/mobilityAPI.js";
const app = express();
//for mobility URL
app.use("/", mobilityRouter);
When I copy past the 'mobilityRouter' function and use it in the import file it works perfectly, but once I put it in another file and exports it I have a "cannot GET/" in my browser. Thank you for your help.
You have different instances of router in both files. Either pass router as a parameter to the function in the other file or export & import in your routerLogic.js.

Typescript & Express: Export several routes from single index.ts file to prefix with ''/api/v1"

I am trying to tidy up my routes. I would like to have 1 file,index.ts, to export all my routes from. I have seen something similar done in plain JavaScript but not sure on the syntax in typescript.
The error I get is: TypeError: Router.use() requires a middleware function but got a Object
(old but works)BaseRoutes.ts
import * as express from 'express';
import {PostRoutes} from '../PostRoutes';
import {CspRoutes} from '../CspRoutes';
import {CustomerPreferenceRoutes} from '../CustomerPreferenceRoutes';
import { SalesOrderRoutes } from '../SalesOrderRoutes';
let app = express();
const BASE_API: string = '/api/v2';
class BaseRoutes{
get routes(){
app.use(BASE_API, new PostRoutes().routes);
app.use(BASE_API, new CspRoutes().routes);
app.use(BASE_API, new CustomerPreferenceRoutes().routes);
app.use(BASE_API, new SalesOrderRoutes().routes);
return app;
}
}
export {BaseRoutes}
(new does not work)BaseRoutes.ts
import * as express from 'express';
let routes = require('../index');
let app = express();
const BASE_API: string = '/api/v2';
class BaseRoutes{
get routes(){
app.use(BASE_API,routes);
return app;
}
}
export {BaseRoutes}
PostRoutes.ts
import * as express from 'express';
import {PostController} from '../../controllers/PostController'
let router = express.Router();
class PostRoutes{
private _postController:PostController;
constructor(){
this._postController = new PostController();
}
get routes(){
let controller = this._postController
router.get('/posts',controller.retrieve)
router.get('/posts/:_id',controller.findById)
return router;
}
}
export{PostRoutes};
index.ts
export * from './PostRoutes';
export * from './SalesOrderRoutes';
It is because you messed up your imports.
export * from './PostRoutes';
export * from './SalesOrderRoutes';
You are re-exporting all the exports from PostRoutes and SalesOrderRoutes etc. , so when you finally import it in BaseRoutes , you actually import all the constructors you exported in each route.
What you want to do is:
import { PostRoutes, SalesOrderRoutes } from '../index';
And then use() each route explicitly.
Edit: You can read more about Typescript modules and Javascript modules

Koa.js route() is not a function

I just made simple koa app that returns rss xml by tag using parameter. and seems like middleware can't read router from router file. I have no idea why It doesn't work. I'm running this app.js with babel-node. and It keeps saying this error below
app.use((0, _koaLogger2.default)()).use((0, _routes2.default)());
^
TypeError: (0 , _routes2.default) is not a function
route/index.js
import Router from 'koa-router'
const router = new Router({ prefix: '/'})
router.get('/:tag', async (ctx, next) =>
(ctx.body = await rssGenerator(this.param.tag)))
export default router
app.js
import Koa from 'koa'
import logger from 'koa-logger'
import routes from './routes'
const app = new Koa()
const port = process.env.PORT || 3000
app
.use(logger())
.use(routes())
app.listen(port, () => console.log("[!] Server STARTED"))
I see 2 problems here in your code:
First: you are importing routes like this:
import routes from './routes'
but in your code above the path is route/index.js and not routes
Second: in route/index.js you are exporting router
export default router
but then you are trying to import routes

Categories