Updated

San Francisco, CA (SportsNetwork.com) - Buster Posey's two-run homer in the eighth inning helped the San Francisco Giants to a 4-2 win over the New York Mets on Friday.

Angel Pagan walked to begin the eighth and Posey crushed the second pitch he saw from Carlos Torres (2-3) into the seats in left-center that gave the Giants the lead.

"Walks are killing us," Mets manager Terry Collins said. "It's certainly something you learn when you come up in this game, walks will burn you."

Jeremy Affeldt (1-1) earned the win in relief of Matt Cain, who carried a no- hitter through five innings.

Cain made his return to the mound after a stint on the disabled list with a strained right hamstring and allowed two runs on three hits with three strikeouts in the no-decision.

"You're excited to get back out there," said Cain. "You're thinking about just finding a good rhythm. For me I kind of recognize (the no-hitter), so I recognized that really early."

Sergio Romo toed the slab in the ninth and picked up his 19th save of the season after a perfect frame.

Posey went 3-for-4 on the night and Brandon Crawford knocked in the other two runs for San Fran (40-21), which has won eight of its last 10 and became the first team in the major leagues to reach 40 wins.

Mets starter Jon Niese went toe-to-toe with Cain for most of the night, surrendering two runs on five hits with three punchouts before leaving it in the hands of his bullpen.

New York has dropped its last four games as it closes a 10-game road trip with a three-game set in the Bay Area.

"I don't look at what the other guy does, I just go out there to give up the least amount of runs as possible," Niese said. "I made that mistake in the seventh and it should have been a different ballgame."

San Francisco opened the scoring in the fifth when Brandon Hicks tripled to center with one out and scored on Crawford's sacrifice fly to left.

Ruben Tejada then opened the top of the sixth with an infield single to break up the no-hit bid from Cain, but New York couldn't muster anything from there.

The Mets did, however, break through in the seventh, as Matt den Dekker doubled to lead off the frame and Daniel Murphy chased him home with his fourth homer of the season to give the visitors a lead.

San Francisco answered in the home half of the seventh after a run-scoring hit from Crawford. Hicks walked, advanced to second on a wild pitch and scored when Crawford ripped a single into center that tied the game at 2-2.

Game Notes

Cain also missed time in late April after cutting his finger on a kitchen knife ... The Giants designated left-hander David Huff for assignment. In 16 relief appearances this season, Huff owns a 1-0 record with a 6.30 ERA ... Tejada had two of New York's four hits ... Hicks collected two hits in the win.