建立服务器连接

默认情况下,MSW 不会与实际服务器建立 WebSocket 连接。但是,你可以在事件处理程序中的任何位置通过调用 server.connect() 来建立此类连接。

¥By default, MSW does not establish a WebSocket connection to the actual server. You can, however, establish such a connection at any point in your event handler by calling server.connect().

const api = ws.link('wss://api.example.com')
 
export const handlers = [
  api.addEventListener('connection', ({ server }) => {
    server.connect()
  }),
]

在上面的例子中,server.connect() 将与底层 WebSocket URL ('wss://api.example.com') 建立一个新的、绕过的 WebSocket 连接。

¥In the example above, server.connect() will establish a new, bypassed WebSocket connection to the underlying WebSocket URL ('wss://api.example.com').

API 参考

¥API reference

server.connect()

The `server.connect()` API reference.

管理连接

¥Managing the connection

建立连接后,server 对象将成为管理该连接的入口点。例如,你可以通过向 server 对象添加 error 监听器来监听原始连接错误:

¥Once you establish the connection, the server object becomes your point of entry to managing the said connection. For example, you can listen to the original connection erroring by adding an error listener to the server object:

server.connect()
server.addEventListener('error', (event) => {
  // Handle the original connection error.
})

探索 “服务器事件” 部分,了解更多关于管理服务器连接的方法。

¥Explore the “Server events” section to learn more about all the ways to manage server connections.

事件转发

¥Event forwarding

请记住,一旦建立了原始服务器连接,所有服务器事件都将转发到客户端,所有客户端事件也将转发到原始服务器。了解如何管理该转发:

¥Bear in mind that once the original server connection has been established, all the server events will be forwarded to the client, and all the client events will be forwarded to the original server. Learn how to manage that forwarding:

Server-to-client forwarding

Manage the server event forwarding.

Client-to-server forwarding

Manage the client event forwarding.