Purcell effect in the gain and spontaneous emission of nanolasers