skip to Main Content

I am working on an Angular project and I have login page and during submitting login API, I am facing CORS error. I am attaching screenshot of it also. Any suggestion would be appreciated.

 API Service.ts:

           constructor( private http: HttpClient ) { }
              httpOptionsPost = {
                headers: new HttpHeaders({
                  'Content-Type': 'application/json',
                  'Access-Control-Allow-Origin': '*',
                  'Access-Control-Allow-Credentials': 'true',
                  'Access-Control-Allow-Methods' : 'GET, POST, OPTIONS',
                  'Access-Control-Allow-Headers' : 'Origin, Content-Type, Accept, X-Custom-Header, Upgrade-Insecure-Requests',
                })
              };
        
              httpOptionsGet = {
                headers: new HttpHeaders({
                  'Content-Type': 'application/json',
                  'Access-Control-Allow-Origin': '*',
                })
              };
        
              _login(username, password) {
                const url = this.domain + '/api/login?username='+username+'&password='+password;
                return this.http.post(url, {}, this.httpOptionsPost);
              }

Login Component: 

    this.apiService._login(data.username, data.password).subscribe((resp: any) => {
          const resobj = JSON.parse(JSON.stringify(resp));
          console.log(resobj);
    })
        
        

Screenshot to show error

6

Answers


  1. I’m not quite familiar with Angular. However, I had the same CORS issue with Vue.js and the solution is to change the add these lines :

    module.exports = {
      
        devServer: {
            proxy: 'https://yourdomain'
        }
        
      
    }
    

    and also replace the https://yourdomain/login to localhost when you do .get or .post, for example : 'http://localhost:8082/login'

    I’m not sure if this would work for you since I am also very new at this, but it did work for me.

    Login or Signup to reply.
  2. Before browser makes a call to your API URL from the angular client application, it will send a preflight request (An HTTP OPTIONS call). this will happen only when your client side application and server side applications are residing in different sub domains or domains. It is the responsibility of the server side application to control whether the cross origin request should be served or not. I see that you are setting the CORS headers in your request header. but it should be received from the API server. so remove that from the angular end and make the proper changes in the server side code.

    Login or Signup to reply.
  3. By default, the Same-Origin-Policy (SOP) forbids request to a different resource. Everything should be loaded from the same source. This is to prevent websites to load data from different servers without the users knowledge. However, there are circumstances where this is required. To cover such case and still provide high safety measurements, CORS was created.
    With CORS it is possible to send requests to a server different than the original one.
    For this the webserver which is receiving the request must be configured accordingly. In your case this means, you have to adjust the CORS settings in the application which is providing the login API you are calling and allow localhost:4200 to be able to send CORS requests.

    Login or Signup to reply.
  4. You need to set up proxy configuration for running the app locally.

    A short example is:

    // create a file proxy.config.json
    {
      "/api": {
        "target": "http://example.com/", // put your actual domain
        "secure": false // true or false depending on your needs.
      }
    }
    

    Then run your project passing the proxy conf to ng-serve or configure it in the package.json.
    For instance:

    ng serve --proxy-config proxy.conf.json
    

    or

    npm start -- --proxy-config proxy.conf.json
    

    Or simply configure it in the angular.json.

    Then, in your code, remove the usage of the domain, or assign the domain to localhost using environment.dev.ts if the domain is not the same as where you are going to deploy you app.
    I’m referring to the domain variable in this block.

    _login(username, password) {
        const url = this.domain + '/api/login?username='+username+'&password='+password;
        return this.http.post(url, {}, this.httpOptionsPost);
    }
    

    More details in https://www.positronx.io/setting-up-angular-proxy-configuration-via-angular-json/ and / or in the official webpack site for advanced proxy configurations

    Login or Signup to reply.
  5. Cors preflight should be handled at server side code. In your case try adding below annotation onto your controller class.

    @CrossOrigin("*") 
    @PostMapping("/user")
    public User userController(){
    
    }
    

    And hope you have a configuration class for handling the CORS, if not try adding one. Sample code for reference.

    @Configuration
    public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        List<String> allowedMethods=new ArrayList<>();
        allowedMethods.add("GET");
        allowedMethods.add("POST");
        allowedMethods.add("PUT");
        allowedMethods.add("DELETE");
        CorsConfiguration cors=new CorsConfiguration();
        cors.setAllowedMethods(allowedMethods);
    
         http.cors().configurationSource(request -> cors.applyPermitDefaultValues());
    
        http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests().requestMatchers(EndpointRequest.to("loggers")).hasRole("ADMIN").and().httpBasic();
    
    }}
    
    Login or Signup to reply.
  6. in your question , the pc_coder answer is right:
    cors is related with backend. Be sure you allowed from api to reach requests

    like the link:
    How does Access-Control-Allow-Origin header work?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search