You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Vite添加简单的JSON API接口?

在Vite中直接实现/api/status接口返回JSON响应

你可以通过Vite的configureServer钩子添加自定义中间件,无需额外启动服务器或配置proxy,就能让/api/status接口返回指定JSON响应:

import { defineConfig } from 'vite'

export default defineConfig({
  server: {
    configureServer(server) {
      server.middlewares.use('/api/status', (req, res) => {
        res.setHeader('Content-Type', 'application/json')
        res.end(JSON.stringify({ ok: true }))
      })
    }
  }
})

这段配置会在Vite开发服务器启动时自动注入中间件,当访问http://localhost:5173/api/status时,就会得到{"ok": true}的响应。

内容的提问来源于stack exchange,提问作者Alex Craft

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 17:20:53