Web服务器中的Javascript HttpRequest POST Access-Control-Allow-Origin错误

时间:2017-05-07 12:56:11

标签: javascript python json post httprequest

我尝试用JavaScript做HttpRequest。因为我之前收到过Access-Control-Allow-Origin错误,所以我使用了Python的SimpleHTTPServer。但我仍然收到了Access-Control-Allow-Origin错误消息。还有另外一种方法吗? javascript有什么问题吗?

这是我的代码。

服务器需要:

  • 基本授权
  • '接受':'application / json'
  • 'Content-Type':'application / json'
  • 'Content-Length':'*'
  • JSON撰写的正文

我使用的是Chrome浏览器。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script language="javascript" type="text/javascript">
     function OnButtonClick() {

  var clientId = "-my ID-";
  var clientSecret = "-my password";

  var authorizationBasic = window.btoa(clientId + ':' + clientSecret);

  var request = new XMLHttpRequest();

  request.open('POST', "-my url-");
  request.setRequestHeader('Authorization', 'Basic ' + authorizationBasic);
  request.setRequestHeader('Accept', 'application/json');
  request.setRequestHeader('Content-Type', 'application/json');
  request.send(JSON.stringify({email: "-my email-" }));

    request.onreadystatechange = function () {
        if (request.readyState === 4) {
           alert(request.responseText);
        }
      };
 }
</script>
</head>
<body>
  <input id="Button1" type="button" value="送信" onclick="OnButtonClick();" />
  <div id="output"></div>
</body>
</html>

0 个答案:

没有答案