Conventional wisdom holds that earthworms head to the surface after rain because they can’t breathe. This is still taught to schoolkids, and you can find a lot of detailed explanation online. Most claim that worm trails and air pockets underground become submerged, and the earthworms can’t breathe. It makes sense.
Most researchers, though, dispute this explanation. As Chris Lowe, a researcher at the University of Central Lancashire, points out in Scientific American, earthworms breathe through their skin and require moisture to do so.
Humans drown when their lungs fill with water. This is not possible for earthworms as they lack lungs. Multiple studies have also shown that most earthworm species can survive being submerged in water for two weeks or more. [...] Lately, most popular scientific accounts write off the “drowning worm” idea as a myth. While it is certainly not likely the entire explanation, perhaps we shouldn’t entirely rule it out. Research published in the journal Invertebrate Biology, for instance, found that worm behavior following rain depended on the species. [...] There undoubtedly will be new research and new revelations about the lives and habits of earthworms. Nature’s mysteries are not just “out there” in the wilderness. The common creatures that live around us still hold surprises. Take a moment and observe the phenomenon happening in the natural world, right now, where we live. The surprises and wonders are right under our feet."