4

I'm testing JS with POST. But I didn't get success with that.

Using the code:

<!DOCTYPE html>
<html>
<body>

<div>
testing js...
</div>

<script>
function upload() {
    var method = "POST";
    var url = "http://127.0.0.1:9000/push";

    var xhr = new XMLHttpRequest();

    xhr.open(method, url);

    xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
    
    var text = {"command":"PUSH"};
    xhr.send(text);

}         
upload();
</script>

</body>
</html>

I'm getting the following error:

enter image description here

The weird is that the request header is not being set correctly through the line:

xhr.setRequestHeader("Access-Control-Allow-Origin", "*");

The request header is like this:

enter image description here

Tomasz Jakub Rup
  • 10,502
  • 7
  • 48
  • 49
Fabio
  • 77
  • 2
  • 3
  • 5
  • You have to enable cross origin access on your server too. – Shubham Jan 15 '18 at 13:00
  • `xhr.setRequestHeader` — It's a **response** header, not a request header! – Quentin Jan 15 '18 at 13:16
  • "The weird is that the request header is not being set correctly" — Since it isn't a safe header to put on a request, the browser is asking the server for permission before it does … but as noted above, it doesn't belong on the request in the first place. – Quentin Jan 15 '18 at 13:18
  • `var text = {"command":"PUSH"};` —That's an object, not text. – Quentin Jan 15 '18 at 13:22

1 Answers1

0

Look at the XHR response: Access-Control-Allow-Origin IS present, Origin is null because you are executing it from your local system, upload to a server to see origin populated.

function upload() {
    var method = "POST";
    var url = "http://127.0.0.1:9000/push";

    var xhr = new XMLHttpRequest();

    xhr.open(method, url);

    xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
    xhr.setRequestHeader("Access-Control-Allow-Origin", "*");

    var text = {"command":"PUSH"};
    xhr.send(text);

}

$(document).ready(function(){
$('.upload').click(upload);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="upload">Upload</button>
Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43
  • While that will cause the browser to send an `Origin` header, the question was about the `Access-Control-Allow-Origin` header (which doesn't belong on the request in the first place). – Quentin Jan 15 '18 at 13:17
  • Access-Control-Allow-Origin IS present, but origin cannot be determined. – Mosè Raguzzini Jan 15 '18 at 13:17
  • You trouble is in your server side. you need to allow any origins (*) and also check because you're sending an object so you need to set in you request that you're sending a json. – Mario Junior Torres Perez Jan 15 '18 at 13:26
  • 2
    This answer is very misleading. Setting `Access-Control-Allow-Origin` header on request is totally useless – charlietfl Aug 02 '20 at 14:26