In addition to being a melody, this is also an outline of a harmonic pattern. I suspect Bach is using F natural in the second measure in order to create a secondary dominant chord, specifically V7/IV. Is the next harmony outlining a C-major chord?
EDIT: ok, I looked it up, it is indeed a V7/IV going to a IV chord. Secondary dominants are fairly common, powerful chromatic chords that intensify the harmony progression toward a harmony by borrowing the upcoming harmony's V chord. The IV chord in G major is a C major chord, so Bach borrows the V7 chords from the key of C major (G Dom 7).
FURTHER EDIT: You added the second example after this answer, so, for completeness sake, I'll put my comment up here: Your second example is in the key of e minor, so the D#s aren't even chromatic. That's just the raised leading tone of e minor, forming a garden variety V chord. The C# is also diatonic to e minor, it's just a raised submediant. The sixth and seventh scale degrees are raised so often in minor keys that it is barely even seen as an alteration.