How to restrict access to some origin using cors in express? | Sololearn: Learn to code for FREE!


How to restrict access to some origin using cors in express?

So here is the simple express code that allows request from only http://localhost:3000 const express=require('express'); const app=express(); const port=8080; const path=require('path'); const cors=require("cors"); const corsOption={ origin:"http://localhost:3000", methods:"GET" } app.use(cors(corsOption)) app.use(express.static('public')); app.get('/',(req,res) =>{ res.send("welcome") }); app.listen(port,()=>{ console.log(`Example app listening on port ${port}`); }); But when i make request to above server using curl, curl -H "Origin: http://localhost:4000" -v http://localhost:8080/ i still get the message welcome , why so ? Any help is much appreciated!

8/18/2021 4:56:32 PM


2 Answers

New Answer


Because from what i know CORS is a mechanism for browsers to reject responses if they are not allowed by the server (by checking the Access-Control-Allow-Origin header). The request still reached the server and the server processed it. Curl is a command line tool and not a browser, it doesn't care if the CORS are right it will show the response either way. For better security you should manually check the Origin request header and accept/reject the request before processing. Of course programs would still easily bypass it but js scripts in browsers would not since Origin header is not modifiable, hence preventing some CSRF attacks.


Giorgos D Thanks a lot .