First, note that the Roman army was not simply a swarm of legionaries - there was also the auxilia (in the imperial army; earlier, the republican army also included non-citizen auxiliaries). The auxilia were similar in number to the legions, and included infantry who would fight in close combat with spear and shield, archers, slingers, javelineers, and cavalry. That is, the infantry in the Roman army was approximately half legionaries and half spearmen.
Second, while a long sword has more reach than a short sword, and a spear (or pike) even more reach, a javelin has more reach than a pike, spear, or sword. The Roman legionary was not just a swordsman, but also a javelineer.
The pike phalanx presented Roman armies with a formidable problem, and the javelin (pilum) was a key part of the Roman solution to that problem. Ideally, the enemy phalanx was strongly encouraged to advance by archery, a rain of slingstones, or pila. As the phalanx advanced, the legionaries would throw their pila, and on a good day, the casualties and the terrain would disrupt the advancing phalanx, allowing the legionaries to get in close and fight.
Sometimes, this solution worked, and sometimes if failed. It could be effective, but was not a panacaea.
Third, Rome was better at winning wars than winning battles. Rome won many wars in which they lost many, or even most, of the battles. The Romans could, and did, win wars despite repeated tactical failures on the battlefield.
There has been plenty of discussion of this before. For example, see the discussion by u/Iguana_on_a_stick in the very recent
and my past answers in