Skip to content

CORS Policy Error #1761

@dominic01

Description

@dominic01
  • Mojolicious version: 8.7
  • Perl version: 5.16
  • Operating system: CentOS 7
  • PHP 7.3 Apache 2.4.43

Steps to reproduce the behavior

I keep getting "Access to XMLHttpRequest at 'http://12.34.56.78:8075/' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource." for hello world like web services. This is happening when I call these services through browser or AJAX.

Sample PHP Code:

<!doctype html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
</head>
<body>
<form id="loginform" method="post">
    <div>
        Username:
        <input type="text" name="username" id="username" value="aaaa"/>
        <input type="submit" name="loginBtn" id="loginBtn" value="Login" />
    </div>
</form>
<script type="text/javascript">
$(document).ready(function() {
    $('#loginform').submit(function(e) {
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: 'http://112.34.56.78:8075/',
            data: $(this).serialize(),
            success: function(response) {
                var jsonData = JSON.parse(response);
  
                // user is logged in successfully in the back-end
                // let's redirect
                if (jsonData.success == "1") {
                    location.href = 'my_profile.php';
                }
                else {
                    alert('Invalid Credentials!');
                }
           }
       });
     });
});
</script>
</body>
</html>

Expected behavior

This Mojolicious web service http://112.34.56.78:8075/ returns {text: "Hello World"}
I tried to add the below header as well.
$c->res->headers->access_control_allow_origin('*');

Actual behavior

I am getting the above error in the browser debug console.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions