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

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

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.

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

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

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.