The Prophet ﷺ said, "Spitting in the mosque is a sin, and its expiation is to bury it."
قال النبي ﷺ: البزاق في المسجد خطيئة، وكفارتها دفنها.
Bukhari related it in the Book of Prayer (415), and Muslim in the Book of Masjids (552), both from the hadith of Shuba, who said, Qatada narrated to us, he said, I heard Anas bin Malik, and he mentioned it.In Muslim's version, Shuba said, I asked Qatada about light spitting in the masjid. He said, I heard Anas bin Malik say, I heard the Messenger of Allah ﷺ say, "Light spitting in the masjid is a sin, and its atonement is burying it." Light spitting is lesser than full spitting.Nawawi said, "Know that spitting in the masjid is a sin absolutely, whether one needs to spit or not, rather he should spit into his garment. If he spits in the masjid, he has committed the sin, and he must atone for this sin by burying the spit. This is the correct view, that spitting is a sin, as the Messenger of Allah ﷺ explicitly stated. The scholars said this, but Qadi Iyad has an invalid statement on this matter, the gist of which is that spitting is not a sin except in the case of one who does not bury it. As for one who intends to bury it, it is not a sin, and he argued for this with invalid points. This statement of his is a clear error contradicting the text of the hadith and what the scholars have said. I have drawn attention to it so that no one is deceived by it." End of quote from Sharh Sahih Muslim (41/5).Ibn Hajar preferred Qadi Iyad's view in Fath al-Bari (512/1), saying, "A group agreed with the Qadi, among them Ibn Makki in Tanqib and Qurtubi in Mufhim, and others. What supports them is what Ahmad narrated with a hasan chain from the hadith of Saad bin Abu Waqqas, attributed to the Prophet, 'Whoever coughs up phlegm in the masjid should hide his phlegm so that it does not touch the skin or garment of a believer and harm him.' Clearer still in purpose is what Ahmad also narrated, and Tabarani, with a hasan chain, from the hadith of Abu Umama, attributed to the Prophet, who said, 'Whoever coughs up phlegm in the masjid and does not bury it, it is a bad deed, but if he buries it, it is a good deed.' So he did not make it a bad deed except with the condition of not burying it. Similar to this is the hadith of Abu Dharr in Muslim, attributed to the Prophet. He said, 'I found among the bad deeds of my nation phlegm that remains in the masjid unburied.' Qurtubi said, 'The ruling of a bad deed was not established merely for its occurrence in the masjid, but rather for that together with leaving it unburied.'" End of quote.As for the hadiths that Ibn Hajar cited, their sourcing will follow.