Search code examples
javascriptnode.jsexpresscors

How to allow Cross-Origin using vite and express


I have two servers running on my computer. Server 1 uses Vite, and Server 2 uses Express.

The home page (Server 1) has this script tag in it to call functions.

<script src="http://localhost:9050/Test" type="module"></script>

The problem is that I can't access Server 2 due to CORS. I have looked this up for a while, and all I know is that I need to set a CORS header. How do I do this in Vite?


As soon as I posted this, I just realized that even if I did get a script from Server 2, Server 1 is still going to run the functions, so once I can get the script, I'm going to use an iframe or embed element so Server 2 runs the functions.

---------- Edit ----------

I'll admit, this is a duplicate question, but I'm new to setting up server stuff, so I'm too naive to understand the answers. Do you guys have an answer for dummies (I would like if you could also tell me some server terms just for my knowledge)? Here is the question.


Solution

  • I belive the configuration for CORS on server 2 is setup in Express, not Vite. You'll probably need to setup your express server to allow requests coming from your server 1 origin.

    app.use(cors({
      origin: ['http://example.com', 'https://example.net']
    }));
    

    Source

    Replace example.com with server 1's address.

    Alternatively, you could use vite as a server proxy for your express.js server - meaning that any requests to the express.js server are directed to vite at a given URL, e.g server1.com/api and then vite forwards them to your express server. For more information see the vite docs.