0

I just want to send a POST Request to the pastebin API and post a paste. (Vanilla JS) My problem is, that this error accours when sending the request, even if I set the header like below: "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." I get the input from the index.html which I then put into the body. (For anyone who isnt familiar with the pastebin api: https://pastebin.com/doc_api)

My index.html:

<script src="hello.js"></script>
<input id="input" type="text" placeholder="Paste Text" />
<button onclick="hello()">Send</button>

My script.js:

function hello() {
  let request = new XMLHttpRequest();
  var input = document.getElementById("input");
  var body = {
    api_dev_key: "--insert your private dev key--",
    api_option: "paste",
    api_paste_code: input,
  };
  request.open("POST", "https://pastebin.com/api/api_post.php");
  request.setRequestHeader("Access-Control-Allow-Origin", "*");
  request.send(body);
  request.onload = () => {
    console.log(request);
    if (request.status === 200) {
      console.log(JSON.parse(request.response));
    } else {
      console.log(`error ${request.status} ${request.statusText}`);
    }
  };
}
Dragon
  • 1
  • 2
  • Check the allowed headers in the http request/response – Iter Ator Apr 06 '21 at 22:49
  • 1
    Their website does not have cross-domain requests enabled, which effectively means they don't want browser scripts from other domains to use their API directly (because they don't want XSS attacks to be directed at their users). You need a proxy server-side script that will accept your requests from your web-page and then send them to pastebin from the server (no cross-domain rules exist there), and then route any useful results back to your script. [An example.](https://stackoverflow.com/questions/29837162/bypassing-cors-with-php-and-javascript-ajax) – alx Apr 06 '21 at 23:01
  • thx for the answer – Dragon Apr 07 '21 at 09:12

0 Answers0