-1

I am pretty new to AngularJS, APIs and coding in general. I created this AngularJS app that let's the user make a post request to an API that I have created. It is a simple parenthesis checker, and everything works fine, except that I have to activate the CORS addon in my chrome browser to make it work, which I can not ask users to do.

I am pretty sure there is a way around this but I don't really understand it. I think I need to add some headers to my http request code, right?

Here is my angularjs service that makes the requests:

function ApiService($http) {
    // API = '//localhost:3000/parentheses';
    API = 'https://parentheses-api.herokuapp.com/parentheses';
    this.getUser = (entry) => {
        // console.log(this.entry);
        return $http
            .post(API, { string: entry} )
            .then(function (response) {
                // console.log(response.data);
                return response.data;
            }, function (reason) {
                // error
            })
        // this.entry = "";
    };
};

angular
    .module('app')
    .service('ApiService', ApiService);

I think this is where I should add the headers. But how and what headers exactly? I don't really get it at this point.

Here is the full project with 2 folders, one containing the API and the other containing the APP where the code above is located (ApiService.js)

Any help would be very much appreciated!

Olivier Girardot
  • 389
  • 4
  • 16
  • 1
    If CORS could be circumvented by adding headers *on the client-side*, having CORS in the first place would be an exercise in futility. Those headers need to be added on the server's reply, not the request. –  Oct 05 '20 at 20:02

1 Answers1

1

If you are requesting an API that is served from a different domain as your frontend, then your API backend will need to respond with the correct CORS headers. Take a look at: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

Access-Control-Allow-Origin: *

This tells the browser to allow requesting code from any origin to access your API.

Alternatively, using Access-Control-Allow-Origin: <origin> tells the browser to only allow the origin specified to access your API.

dwosk
  • 1,202
  • 8
  • 11
  • OK, let me try this on my API (not my front end, got it!) and if I don't make it, I'll post a new question, sharing my API this time :) Thanks a lot for your help! – Olivier Girardot Oct 06 '20 at 07:52