0

I`m working on a project in JavaScript and basically what I want is to send a post request to my server in order to perform a login. So I do that as it fallows: in Index.html

     <input type="button" name="" value="Login" id="login" onclick=doLogin() onsubmit="return false">

and I have a user.js

function doLogin() {

    let email = $('#emailLogin').val().trim();
    if(email === ""){
        email = null;
    }

    let password = $('#passwordLogin').val().trim();
    if(password === ""){
        password = null;
    }
    sendLoginRequest(email,password,getLoginSuccessHandler,getLoginErrorHandler);

}
function sendLoginRequest(email, password, successHandler, errHandler) {

    localStorage.removeItem('auth');
    localStorage.setItem('auth', btoa(email + ":" + password));

    let data = {email: email, password: password};

    jQuery.ajax({
        type: 'POST',
        url: getURL() + "user/login",
        contentType: "application/json",
        headers: { 'Authorization' : 'Basic ' + getAuth()
        },

        data: JSON.stringify(data),
        dataType: "json",
        accepts: "application/json",
        success: function (data, status, jqXHR) {
            successHandler(data);

        },

        error: function (jqXHR, message) {
            errHandler(jqXHR.responseText.message);
        }

    });

}

So when I press the button the page will send an OPTIONS request not a POST request. And in the console the message it printed like that: HTTP403: FORBIDDEN - The server understood the request, but is refusing to fulfill it. (XHR)OPTIONS - http://localhost:port/user/login

NeagDB
  • 47
  • 1
  • 2
  • 10
  • You need to configure your server to handle CORS Options is bieng sent by browser to check if POST method is supported by the endpoint you mentioned which allows it to save bandwith if POST if big Refer here https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request Upvote if it helped – Abhishek Mathur Nov 09 '19 at 11:30
  • thank you both both answers helped me to clarify the problem. – NeagDB Nov 09 '19 at 12:20

1 Answers1

0

It's possible your server is throwing a CROSS Origin error, you need to enable CORS on your server by adding these flags in the response of your server.

headers.add("Access-Control-Allow-Origin", "*");
headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");  
//If you have some custom headers please add below
headers.add("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, {your-custom-header}");

If you quickly want to test your API & Login Flow you can use any of the plugins on chrome extention to allow CORS for you. However, this is not a permanent solution like the one given above.

Ayyub Kolsawala
  • 809
  • 8
  • 15