Why would a web application try to connect to a port on
A simple explanation that doesn't involve malicious acting is developmental tasks. Depending on the environment, some developers may install a local, lightweight copy of the backend API on their development machine. This would allow the frontend code to try and connect to localhost and do its things on the developer machine, rather than the production backend.
Why would such a code be in a production app?
It wouldn't be unheard of that someone accidentally pushed code to the wrong branch. I've seen plenty of debug code in production releases. With a big enough codebase and enough developers, someone, somewhere will push some debug code to production, sooner or later.
Are there other explanations?
Yes, certainly. Banks have, depending on the jurisdiction, many obligations they need to fulfill. As you may know, politics is as much about personal image as it is about the actual effect of policies. So some politicians may try to boast that they pushed some regulation that forces banks "to do security stuff", which ends up in regulations like "Banks have to detect if end-users have malware on their computer and warn them".
This sounds good to politicians and other non-tech users, but when these policies then end up in the hands of developers and system administrators, who then have the unfortunate task of implementing these, it quickly turns into a nightmare.
So what do banks usually do in such cases? They buy some software that claims to do exactly that. What does that software do? God knows, but it ticks the checkbox, and that's good enough. What the software actually does isn't important, as long as they can claim it does something. And searching for open ports on the system of the user seems like a good thing to do.
Can this be dangerous for me?
It might have adverse side effects for you. Depending on what the software is set out to do, it may detect legitimate software on your PC as malware and alert the bank that you have malware on your PC. Depending on how the bank is run internally, this might mark you as a "risk user" and give you worse conditions down the line.
Of course, this is very speculative, but it is a risk nonetheless. It also could mess with the software you have on your PC. Simply the act of attempting a new connection could cause your application to react differently, and thus adversely to what you may have intended to do.
Finally, the bank or other website may also detect certain local applications and use this to profile you in different way, such as "Web Developer" or what not. This may be information you consider none of the bank's business.
Is this legal?
I am not a lawyer and I can't answer for the legality of this practice. If you care about your own bank, then I suggest contacting a lawyer in your area. They will certainly be equipped to answer your concerns in regards to your applicable jurisdiction.