There is a definite connection between the notes of the melody and the notes of the chord.

This is a big subject and musicians love to break the rules, so this explanation will be short and imperfect—but should give you the basic idea.

You can think about it as “which chords fit this melody?” or “what melody would go with these chords?”: a song can be written either way round!