1

Here is my curl command that was given by my backend engineer. It works fine in command line. I need to translate that to reactjs. I couldn't do that, so I am trying to do that with ajax.

curl -v -H "Origin: http://example.com" -H "Access-Control-Request-Method: POST" -H "Access-Control-Request-Headers: X-Requested-With" -H "Authorization: ELS <your_token_here>" -X OPTIONS  "localhost:9000/proj/user/token/<your_token_here>"

JS:

  _login(username,password){
    console.log(username+password)
    $.ajax({
        type: 'POST',
        contentType:'application/json',
        url: 'http://localhost:9000/proj/user/token',
        beforeSend: function(xhr) {
             xhr.setRequestHeader("Origin", "http://localhost:3000");
             xhr.setRequestHeader("Access-Control-Request-Method", "POST");
             xhr.setRequestHeader("Access-Control-Request-Headers", "X-Requested-With");
             xhr.setRequestHeader("tokem", token);

        }, success: function(data){
            console.log(dtata);
        }, error: function(e){
            console.log(e);
        }
    })
  }

I get errors like jquery-2.2.4.min.js:4 Refused to set unsafe header "Origin" etc.

Barmar
  • 741,623
  • 53
  • 500
  • 612
tv3free
  • 173
  • 1
  • 19

1 Answers1

0

Using JavaScript in a webbrowser, you cannot do the same requests as you can do manually with cURL for example. This is because of security regulations. On of them is that you cannot set the Origin header. The browser enforces that the Origin header is the real 'origin'. See also: Chrome Extension: how to change origin in AJAX request header?

So try if it works as expected without setting the Origin header.

Community
  • 1
  • 1
Jeroen Noten
  • 3,574
  • 1
  • 17
  • 25
  • You are right. I cannot set up ajax request header. I found out what was the issue with my call. I was passing wrong request headers (username, pwd). Once I removed that, it started working. Thanks for your reply. – tv3free May 27 '16 at 15:06