3

I just started my nodejs express template buy cors is not working.

I used npm install cors --save

here is the file:

var express = require('express'); var cors = require('cors'); var app = express(); app.use(cors()); var corsOptions = { origin: 'https://example.com/', optionsSuccessStatus: 200 }; app.get('/', cors(corsOptions), function(req, res, next) { res.json({ message: 'hooray! welcome to our api!' }); }); app.get('/tt', function(req, res, next) { res.json({ message: 'hooray! welcome to our api!' }); }); var port = process.env.PORT || 3030; app.listen(port); console.log('Magic happens on port ' + port); 

Now with the above code when I access localhost:3030/tt or / I still see the content and I shouldn't

What's wrong with this.. I just lost like 2 hours working on this.. :( At this time I would like not to use CORS, but in near future when my app is finished, I want to allow incoming calls only from my project, since this app will be my API.

1 Answer 1

4

The behavior you are describing seems is what I would expect.

CORS won't help you filter out incoming calls on the server. In this case the browser's CORS check won't kick-in as it appears you are directly typing in the URL in the browser. Browser does a CORS check only when the the webpage loaded from a particular domain tries to access/submit to a URL in a different domain.

A different way to think about CORS. CORS is intended to protect the user sitting in front of the browser, and not the server-code that is being accessed.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you for your reply. How would it best be to prototect my apiserver.com to allow access only from mywebpage.com ?
API user authentication and tokens will help you only allowing you using the API

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.