简体   繁体   中英

How to import routes in polka js similar to express.Route()

I am trying to import route logic from another file. In express js this is achievable via express.Route(), when i tried polka.Route() an error pops up saying Route doesn't exist in polka.

Express Implementation

server.js

const express = require('express');
const users = require('./routes/api/users');
const app = express();    
app.use('/users', users);

user.js

const express = require('express');    
const router = express.Router();    
router.get('/test', (req, res) => res.json({ msg: 'works' }));    
module.exports = router;

When /users/test is hit the output is {msg:'works'}. This works for the express implementation. For the polka implementation i changed the word express to polka installing it. The issue arises on the line polka.Router() of user.js. How do i enable this functionality of importing route logic from another file in polka.

The polka micro web server does not implement a difference between routers and the app. In your users.js file simply setup your routes as you would in your server.js file and then module.export . See Below:

Polka Implementation

server.js

const polka = require('polka');
const users = require('./routes/api/users');
const app = polka();    
app.use('/users', users);

user.js

const polka = require('polka');    
const router = polka();    
router.get('/test', (req, res) => res.end(JSON.stringify({ msg: 'works' })));    
module.exports = router;

Hope this help!

Also, here is a good link to see other differences between Express.js and Polka.js : https://github.com/lukeed/polka#comparisons

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM