Skip to content

Basic Examples ​

Request Intercept ​

Intercept the api/test interface request and respond with data:

ts
import { defineMock } from 'vite-plugin-mock-dev-server'

export default defineMock({
  url: '/api/user',
  body: {
    name: 'Mark',
    age: 18,
  },
})

Allow Request Methods ​

Configure the allowed request methods for the current interface

allow-method.mock.ts
ts
import { defineMock } from 'vite-plugin-mock-dev-server'

/**
 * Method matching examples.
 *
 * A request with an undeclared method does not match these rules and falls through
 * to the example's JSON 404 (`plugins/api-404.ts`), so POST to the GET-only rule and
 * PUT to the GET+POST rule are real 404s instead of a global fallback response.
 *
 * 请求方法匹配示例。
 *
 * 未声明的方法不会命中这些规则,而是落到示例的 JSON 404(`plugins/api-404.ts`)。
 * 因此对仅 GET 规则发 POST、对 GET+POST 规则发 PUT 都会得到真实的 404,
 * 而不是全局兜底响应。
 */
export default defineMock([
  {
    url: '/api/only-get-method',
    method: 'GET',
    body: {
      message: 'Only get request methods are allowed',
    },
  },
  {
    url: '/api/allow-get-and-post',
    method: ['GET', 'POST'],
    body: {
      message: 'Allow get and post request methods',
    },
  },
])

Response Status ​

Configure the response status code and response status text for the current interface.

Generally, it is only necessary to explicitly specify the status code, and the plugin will internally set the corresponding status text based on the status code.

fail.mock.ts
ts
import { defineMock } from 'vite-plugin-mock-dev-server'

export default defineMock({
  url: '/api/fail',
  status: 404,
})

Enable/Disable Mock ​

Configure to enable or disable a specific mock request.

ts
import { defineMock } from 'vite-plugin-mock-dev-server'

export default defineMock({
  url: '/api/test',
  enabled: false,
})

After setting enabled to false, the /api/text requests will no longer go through the mock-server, but will be forwarded by the original server.proxy configuration.

Dynamic Path Matching ​

dynamic-match-url.mock.ts
ts
import { defineMock } from 'vite-plugin-mock-dev-server'

const authorMap: Record<string, any> = {
  10001: { id: '10001', name: 'Mark', age: 20 },
  10002: { id: '10001', name: 'John', age: 21 },
}

export default defineMock({
  url: '/api/author/:id',
  body(request) {
    const id = request.params.id as string
    if (id && authorMap[id]) {
      return {
        code: 200,
        message: 'success',
        result: authorMap[id],
      }
    } else {
      return {
        code: 400,
        message: 'author not found',
      }
    }
  },
})

Response Delay ​

delay.mock.ts
ts
import { defineMock } from 'vite-plugin-mock-dev-server'

export default defineMock([
  {
    url: '/api/delay',
    delay: 6000,
    body: {
      message: 'delay 6 seconds.',
    },
  },
  {
    // delay 6 seconds. but request fail
    url: '/api/delay-and-fail',
    status: 504,
    delay: 6000,
  },
])

Released under the MIT License