在 Vue/Quasar SSR 项目中创建 API

wir*_*uma 7 vue.js quasar-framework

我想创建一个可以由应用程序本身(无论是“ajax”还是服务器渲染)和其他客户端(例如移动应用程序)调用的 API。我在谷歌搜索“Quasar REST API”时发现的大多数文章都在谈论如何访问外部 API,这不是我的情况。

我的理解是修改src-ssr/extension.js

module.exports.extendApp = function ({app, ssr}) {
    app.get('/api/bla', (req, res) => {
        res.send('something')
    })
}
Run Code Online (Sandbox Code Playgroud)

并确保port内部src-ssr/index.js

const
    ssr = require('../ssr'),
    extension = require('./extension'),
    app = express(),
    port = process.env.PORT || 8888
Run Code Online (Sandbox Code Playgroud)

匹配中的值quasar.conf.js

    devServer: {
        https: false,
        open: false,
        port: 8888,
    },
Run Code Online (Sandbox Code Playgroud)

项目构建并成功运行,但http://localhost:8888/api/bla一直在浏览器中加载。我想念什么?

Dav*_*olf 0

在这里查看我的回答。


  • src-ssr/middlewares/api.ts自定义中间件来捕获命中/api/*,当找到配置的路由时,将加载并执行 api 处理程序
import { ssrMiddleware } from 'quasar/wrappers'
import routes from '../../src/api/_routes'
import type { Request, Response } from 'express'
import { parse } from 'url'

export default ssrMiddleware(async ({ app, resolve }) => {
    app.all(resolve.urlPath('*'), async (req: Request, res: Response, next) => {
        const { pathname } = parse(req.url)
        if (!pathname || !pathname.startsWith('/api')) {
            return next()
        }

        const path = pathname.replace(/^\/api/, '')

        if (!Object.keys(routes).includes(path)) {
            res.sendStatus(404).end()
            return
        }

        console.log(`API hit on ${path}`)

        try {
            const handler = (await routes[path as keyof typeof routes]())
                .default
            handler(req, res)
        } catch (error) {
            console.error(error)
            res.sendStatus(500).end()
        }
    })
})

Run Code Online (Sandbox Code Playgroud)
  • 您可以像这样配置您的 api 路由src/api/routes.ts
const routes = {
    '/ping': () => import('./ping'),
}

export default routes
Run Code Online (Sandbox Code Playgroud)
  • 并写下你的 api 路由,例如src/api/ping.ts
import type { Request, Response } from 'express'

export default function (req: Request, res: Response) {
    res.status(200).send('pong')
}
Run Code Online (Sandbox Code Playgroud)