如何在单个文件中拥有多个服务器(工兵)获取、发布等路由?

Ste*_*veO 3 svelte

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

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

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

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

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

Ric*_*ris 7

将处理程序添加到您的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);
    });
Run Code Online (Sandbox Code Playgroud)

  • @Rich Harris我想补充一点,只有当`"polka": "next"`安装在`package.json`中时才是正确的,目前它通过`npm ls polka`评估为`polka@1.0.0-next .11`。看起来最新稳定版本的“^0.5.2”正在向以这种方式定义的每个路由返回 404。换句话说,一旦我将 polka 版本号放入 package.json 中,我就只能通过路由页面/服务器路由在干净的 sapper `^0.27.9` 中定义路由。 (2认同)