Node.js express cors problem

I hae install on a windows vps a node.js express webserver and a website with ejs template, when i call localhost on the vps server browser it works, and i have open port 80 for the vps server but when i call the website from outside with webbrowser then i see in the console.log error about cors policy.

In the node js serve file i have include the following code:

let cors = require("cors");
app.use(cors({
    origin: 'http://localhost',
    methods: ['GET', 'PUT', 'POST'], 
    allowedHeaders: ['Content-Type', 'Authorization'],
    credentials: true 
}));

i did think that should help, but it does not, does somebody know how i must setup this to make it ossible for calling the website from outside the vps server?

I am on vacation and have no computer here so I cannot check my projects, but normally you must enter in the origin the address from which you allow requests. As the node server is in the vpn, localhost ist the vpn and not your external browser. So if you want to access the server in the vpn from your local computer this is not localhost for the vpn. To be honest I am not pretty sure what the right entry would be but maybe it is the IP of your computer in the network?

i found a solution, when you write in the html page for all fetch request instead of localhost the server ip adress then it works, but with that cors code in the node js file did not work but changeing the url for the fetch request directly in the html page code

I don’t understand. Of course you must write in the fetch request of the client side the id of your vpn server and not local host.

Cors ( Cross-Origin Resource Sharing) is when you from your page call some other domain, Assume You know it. So to make sure your server is running properly (reachable from outside, remove any cross-origin HTTP requests), Then why browser is complaining, it mean by default it has some restriction, which you can remove with HTTP headers, for what you added npm cors package. Try first for all routes just cors() without options. and learn headers. and you will slowly progress
Hope not answering with direct solution will help You.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.