【问题标题】:How to have multiple server (sapper) get, post, etc routes in a single file?如何在一个文件中拥有多个服务器(工兵)获取、发布等路由?
【发布时间】:2019-09-02 03:39:45
【问题描述】:

我正在使用 sapper 服务器路由,这适用于单个 .js 文件,这些文件将使用文件名作为路由和导出函数 post(req,res,next) 来处理单个 get、post 等。

我想在一个文件中使用我自己的服务器路由(如 Express)和多个处理程序......

app.post('/api/abc', req,res,next)

app.post('/api/def', req,res,next)

这在 Sapper 中是否可行,如果可以,请举个例子?

【问题讨论】:

    标签: svelte


    【解决方案1】:

    将处理程序添加到您的 server.js:

    polka() // Or `express()`, if you're using that
    
        /* add your handlers here */
        .post('/api/abc', (req, res, next) => {...})
        .post('/api/def', (req, res, next) => {...})
    
        /* normal stuff */
        .use(
            compression({ threshold: 0 }),
            sirv('static', { dev }),
            sapper.middleware()
        )
        .listen(PORT, err => {
            if (err) console.log('error', err);
        });
    

    【讨论】:

    • 完美运行。谢谢!
    • @Rich Harris 我想补充一点,只有当"polka": "next" 安装在package.json 中时才适用,目前通过npm ls polka 评估到polka@1.0.0-next.11^0.5.2 看起来像最新的稳定版本正在向以这种方式定义的每条路线返回 404。换句话说,只要我将 polka 版本号放入 package.json 中,我就只能通过路由页面/服务器路由在干净的工兵^0.27.9 中定义路由。
    猜你喜欢
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 2021-08-23
    • 2016-01-23
    • 2020-12-21
    • 2022-11-12
    • 1970-01-01
    • 2013-10-15
    相关资源
    最近更新 更多