enable CORS code example

Example 1: php access origin

<?php
 header("Access-Control-Allow-Origin: *");

Example 2: viacep cors problem

Pra usar basta usar a url:
-- https://proxier.now.sh/api?url=https://viacep.com.br/ws/<SEU_CEP_AQUI>/json

Example 3: Enable CORS in cpanel

# How to enable CORS in your hosting account
# If you are a developer and need CORS enabled to run your app you can enable it adding the following lines in the .htaccess file in your hosting account.

<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>


# Other option is also enable the headers in your script if you are using PHP, for example:

<?php
header("Access-Control-Allow-Headers: Authorization, Content-Type");
header("Access-Control-Allow-Origin: *");
header('content-type: application/json; charset=utf-8');
?>

Example 4: Access to XMLHttpRequest at 'http://localhost/MySQL_pracs/InsertUser.php' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

//Access to XMLHttpRequest at 'http://localhost/[api path].php' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

//The error is simply saying that "Content-Type" is missing from "Access-Control-Allow-Headers".

//Therefore we need to add "Content-Type" to "Access-Control-Allow-Headers".

<?php 
header('Access-Control-Allow-Headers: Content-Type');
-----
?>

Example 5: enable cors

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
            .allowedOrigins("http://domain2.com")
            .allowedMethods("PUT", "DELETE")
            .allowedHeaders("header1", "header2", "header3")
            .exposedHeaders("header1", "header2")
            .allowCredentials(false).maxAge(3600);
    }
}

Example 6: enable cors

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

Tags:

Cpp Example