-1

I received an error attempting to locally access a php file on a remote server for purpose of authentication.

Currently attempting to resolve issue by setting up a CORS proxy to successfully curl the endpoint, unsure if this solution would work out.

Remote server: "http://cop4331-5.com/LAMPAPI/Login.php"

Error: "index.html:1 Access to XMLHttpRequest at 'http://cop4331-5.com/LAMPAPI/Login.php' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."

Javascript:

const urlBase = 'http://COP4331-5.com/LAMPAPI';
const extension = 'php';

let userId = 0;
let firstName = "";
let lastName = "";

function doLogin()
{
    userId = 0;
    firstName = "";
    lastName = "";
    
    let login = document.getElementById("loginName").value;
    let password = document.getElementById("loginPassword").value;
//  var hash = md5( password );
    
    document.getElementById("loginResult").innerHTML = "";

    let tmp = {login:login,password:password};
//  var tmp = {login:login,password:hash};
    let jsonPayload = JSON.stringify( tmp );
    
    let url = urlBase + '/Login.' + extension;

    let xhr = new XMLHttpRequest();
    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-type", "application/json; charset=UTF-8");
    try
    {
        xhr.onreadystatechange = function() 
        {
            if (this.readyState == 4 && this.status == 200) 
            {
                let jsonObject = JSON.parse( xhr.responseText );
                userId = jsonObject.id;
        
                if( userId < 1 )
                {       
                    document.getElementById("loginResult").innerHTML = "User/Password combination incorrect";
                    return;
                }
        
                firstName = jsonObject.firstName;
                lastName = jsonObject.lastName;

                saveCookie();
    
                window.location.href = "color.html";
            }
        };
        xhr.send(jsonPayload);
    }
    catch(err)
    {
        document.getElementById("loginResult").innerHTML = err.message;
    }

}

ADyson
  • 57,178
  • 14
  • 51
  • 63

1 Answers1

0

You should allow Cross-Origin requests to your website.

It could be done using Access-Control-Allow-Origin header on your site's side. You can also adjust CORS options using others Access-Control-* headers

You can check MDN site to learn more about CORS:

  1. Understanding CORS
  2. Access-Control-Allow-Origin header
Yaro
  • 3
  • 3