user7898281
user7898281

Reputation:

Accessing your backend API without using CORS

I'm teaching myself web dev and am just getting into sending XMLHttpRequests from a client-facing page to an Express.js API backend. In this particular case I'm using it to transmit form data and save it to a Mongo Database.

The specific issue I'm having is this: I send it encoded as application/json, which throws me a cross-origin error because the Express.js API is running on http://127.0.0.1:3000. I understand that requests to the same domain but a different port cause this error.

I've been able to get around it by doing npm install cors and then using var cors = require('cors'); and app.use(cors()); in my Express.js source, but as I understand it that will open the API up to requests from anywhere. What if I really do just want it to only be accessible on my own domain? I mean supposing it were a production site mysite.com and the form is at mysite.com/form and the backend is at mysite.com:3000. I think I'm getting those example ideas right, but as I'm new to this I'm not sure.

How can I get them to be running on the same domain so as to not be doing a cross-origin request? Is there a standard way to do this? As of now I feel like to get the backend and the form running on the same port would require serving the form page from the Express.js backend itself, but what if I didn't want Express to be my server? What if I wanted to serve pages some other way, from Apache or something, and just have this form on there that sends its data off to Express for processing? Or if I wanted to have an Angular app running that POSTs data to the Express backend, again for processing?

Thank you!

Upvotes: 1

Views: 1509

Answers (1)

alex3683
alex3683

Reputation: 1565

If you want to stick with CORS, you can configure it to stick to a certain origin: https://www.npmjs.com/package/cors#configuring-cors But keep in mind that this doesn't prevent from someone else accessing your API via a simple curl command. CORS is there to guard the browser, not the API.

A better approach (that you mentioned yourself) would be to have both parts running at the same domain and port. This can be achieved by proxying the requests. In Express you could simply deliver your frontend code as static assets with express.static(). In Apache you could also add some proxying, though I cannot help you there, as I'm not that familiar with Apache modules and setups.

Securing your API from third-party access is another topic. You'll need some form of authentication and authorization. Doing that right can be hard. Perhaps you should have a look at Oauth 2 for a proven standard.

Upvotes: 2

Related Questions