- Framework to choose
- Back-end project setup
- Add the dependent
- Create the project entry file app.js
- Use require-directory to automatically load routes
- The basic grammar
- Automatic loading of Koa routes
- Use Nodemon to start debugging
Want to do a personal blog website a long time ago actually, server domain name also bought very early. I just don’t know why I didn’t make up my mind to do it. This time I was stuck at home because of the epidemic. , rekindled the purpose. No more BB, straight to dry.
Framework to choose
Last year, I learned java-SpringBoot. Then I decided to use Java-Springboot + React /Vue. Think again, a few pages or online directly next template with native + Jquer stem. Finally finalized, the front-end React SSR server node.js + Koa.
Back-end project setup
npm init
Copy the code
Add the dependent
npm install koa koa-bodyparser koa-static
Copy the code
Create the project entry file app.js
const koa = require('koa')
var router = require('koa-router') ();const parser = require('koa-bodyparser')
const app = new koa()
app.use(parser())
router.get('/'.async (ctx)=>{
ctx.body="hello node";
})
app.use(router.routes());
app.on('error', (err, ctx) => {
console.log('Caught! ', err.message);
});
app.listen(8080)
Copy the code
Then go to -http://localhost:8080/ in your browser
Hello Node, Ok, a simple Node service is started.
Use require-directory to automatically load routes
Use the require-directory library to load all modules in a specified folder without requiring require() every timeCopy the code
Add require-directory dependencies
npm install require-directory
Copy the code
The basic grammar
Require-directory can specify the folder or not specify, folder nesting is fine. The default is __dirname, which is the directory name (absolute path) of the current module. We use process.cwd()
One might ask the difference between __dirname and process.cwd()
Process.cwd () is the directory where the node command is currently executed — the working directory. This ensures that the path of the file is always the same when executed in different directories
__dirname is the address of the js file being executed — the directory in which the file resides
If the app directory has home.js and user, the user directory also has login.js and logout.js files
const requireDirectory = require("require-directory");
const modules = requireDirectory(module.`${process.cwd()}/app`);
Copy the code
Modules result in the equivalent of
const modules = {
home: require("./app/home.js"),
auth: {
login: require("./app/user/login.js"),
logout: require("./app/user/logout.js")}}Copy the code
So with that in mind, we’re going to be able to manipulate it.
Automatic loading of Koa routes
const koa = require('koa')
const requireDirectory = require('require-directory')
const Router = require('koa-router')
const app = new koa()
const apiDirectory = `${process.cwd()}/app/api`
requireDirectory(module, apiDirectory, { visit: whenLoadModule })
function whenModuleLoad(obj) {
if (obj instanceof Router) {
InitManager.app.use(obj.routes());
} else if (typeof obj === "object") {
// module.exports is compatible with exports
for (let k in obj) {
if (obj[k] instanceofRouter) { InitManager.app.use(obj[k].routes()); }}}}Copy the code
We create test.js and user in the API directory, and login.js and logout.js in the user directory
const Router = require("koa-router");
const router = new Router()
router.get('/test'.async (ctx, next) => {
ctx.body = "usertest"
})
module.exports = router
Copy the code
Let’s try to write it like an exported object
const Router = require("koa-router");
const router = new Router({
prefix:'/user'
})
router.get('/login'.async (ctx, next) => {
ctx.body = "login"
})
module.exports = {
router
}
Copy the code
Use Nodemon to start debugging
Nodemon is used to monitor any changes in the Node.js application and automatically restart the service, without requiring us to manually restart every time we change the code.
Install Nodemon globally
npm install nodemon -g
Copy the code
Start the app. Js
nodemon app.js
Copy the code
Ok, now let’s go to the browser route in turn
Turns out our routes are all auto-loaded