javascriptexpresscors

How to allow Cross-Origin using vite and express


I am currently running two servers on my local machine: Server 1, which utilizes Vite, and Server 2, which is built with Express.

On the home page of Server 1, I have included the following script tag to call functions from Server 2:

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

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

However, I am encountering an issue with Cross-Origin Resource Sharing (CORS) that prevents me from accessing Server 2 and vise versa. Despite my research, I understand that I need to configure a CORS header, but I am unsure how to implement this in Vite. I know how to do this through Express.

Could you please provide guidance on how to properly set up CORS headers in Vite to resolve this issue?


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.


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.