# Network Requests

Examples of handling AJAX or XHR requests in Cypress, for a full reference of commands, go to docs.cypress.io

#### cy.server()

To control the behavior of network requests and responses, use the `cy.server()` command.

    cy.server().then(function(server){
      // the default options on server
      // you can override any of these options
      expect(server.delay).to.eq(0)
      expect(server.method).to.eq('GET')
      expect(server.status).to.eq(200)
      expect(server.headers).to.be.null
      expect(server.response).to.be.null
      expect(server.onRequest).to.be.undefined
      expect(server.onResponse).to.be.undefined
      expect(server.onAbort).to.be.undefined

      // These options control the server behavior
      // affecting all requests
      expect(server.enable).to.be.true
      expect(server.force404).to.be.false
      expect(server.whitelist).to.be.a('function')
    })

    cy
      .server({
        method: "POST",
        delay: 1000,
        status: 422,
        response: {}
      })

#### cy.request()

To make an XHR request, use the `cy.request()` command.

    cy
      .request('https://jsonplaceholder.typicode.com/comments').then(function(response){
        expect(response.status).to.eq(200)
        expect(response.body).to.have.length(500)
        expect(response).to.have.property('headers')
        expect(response).to.have.property('duration')
      })

#### cy.route()

To route responses to matching requests, use the `cy.route()` command.

    cy
      .server()
      .route(/comments\/1/).as('getComment')
      .get('.network-btn').click()
      // Wait for a specific resource to resolve
      // continuing to the next command
      .wait('@getComment').its('status').should('eq', 200)

      // Specify the route to listen to method 'POST'
      .route('POST', '/comments').as('postComment')
      .get('.network-post').click()
      .wait('@postComment')
      .get('@postComment').then(function(xhr){
        expect(xhr.requestBody).to.include('email')
        expect(xhr.requestHeaders).to.have.property('Content-Type')
        expect(xhr.responseBody).to.have.property('name', 'Using POST in cy.route()')
      })

      message = 'whoa, this comment doesn\'t exist'

      // Stubbed PUT comment route
      cy
        .route({
            method: 'PUT',
            url: /comments\/\d+/,
            status: 404,
            response: {error: message},
            delay: 500
          }).as('putComment')

        .get('.network-put').click()
        .wait('@putComment')
        .get('.network-put-comment').should('contain', message)