express

栏目 Node.js

简单整理一下express,最好做个代码块

启动项目

yarn add axios express bodyparser
node app.js local # 本地测试环境
node app.js debugger # vscode 调试
node app.js # 不带参数共享0.0.0.0

app.js

const express = require("express")
const app = express()
const options = process.argv.splice(2) 
let appPort
if (options.includes("local")) {
    appPort = 3207
} else if (options.includes("debugger")) {
    appPort = 3208
} else {
    appPort = 3206
}
const rIndex = require("./routes/index")
app.use("/", rIndex) 
app.use("*", r404)
app.listen(appPort, () => {
    const url = `http://localhost:${appPort}`
    console.log("server start:")
    console.log(url)

    // 自动打开浏览器
    var start =
        process.platform == "darwin"
            ? "open"
            : process.platform == "win32"
            ? "start"
            : "xdg-open"
    // require("child_process").exec(start + " " + url)
})

router.js

const express = require("express")
const router = express.Router()
router.get("/", async function(req, res) {res.json({})}
module.exports = router