在纯JS

时间:2016-02-06 13:38:08

标签: javascript couchdb cloudant

我正在网页浏览器中编写游戏,我想制作一个高分列表。我希望它可以保存高分,以便用户可以参与竞争,所以我在Cloudant(CouchDB)中创建了一个数据库,我计划上传到该数据库。下载分数。

function uploadHighscores() {
  var req = new XMLHttpRequest();
  req.open('PUT', 'http://reverse-snake.cloudant.com/highscores/highscores', true); // METHOD, url, async
  req.onload = function() { // Asynchronous callback.
    console.log(req.responseText);
    console.log("Scores uploaded");
  }
  req.setRequestHeader('Content-Type', 'application/json');
  console.log("Sending scores...");

  req.send("{\"_id\": \"highscores\", \"_rev\": \"6-f29fd233a21c65e3f4a7485f36c46ae4\", \"data\":{\"scores\":[999, 999, 999, 999, 999], \"times\":[[59, 59, 999], [59, 59, 999], [59, 59, 999], [59, 59, 999], [59, 59, 999]]}}");
}

失败并出现错误:
XMLHttpRequest无法加载http://reverse-snake.cloudant.com/highscores/highscores。预检的响应无效(重定向)

我尝试用curl做这个请求:

curl http://reverse-snake.cloudant.com/highscores/highscores -X PUT -d "{\"_id\": \"highscores\", \"_rev\": \"6-f29fd233a21c65e3f4a7485f36c46ae4\", \"data\":{\"scores\":[999, 999, 999, 999, 999], \"times\":[[59, 59, 999], [59, 59, 999], [59, 59, 999], [59, 59, 999], [59, 59, 999]]}}"

它成功了。我错过了什么?

编辑:每个请求,失败的http请求的日志:http://pastebin.com/D97KwpM1

2 个答案:

答案 0 :(得分:1)

答案很简单。 CouchDB(和Cloudant)需要安全的网络访问。这是由网络日志揭示的:

获取请求转到http:// ...并通过重定向回复;这导致https:// ...

将请求转到http:// ...并使用重定向进行回复;这会导致失败。

需要进行的唯一更改是在第2行,更改方法。不需要设置请求标头。

答案 1 :(得分:0)

您的错误与CORS相关,并且卷曲绕过该检查(这是“安全”功能,但检查由浏览器完成,因此安全性非常弱)。

编辑由于http =>而发生错误https重定向。可以避免重定向,请参阅the other answer,但为什么它无法从浏览器中失败?

这是网络日志:

Request URL:http://reverse-snake.cloudant.com/highscores/highscores
Request Method:OPTIONS
Status Code:307 Internal Redirect
Response Headers
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:null
Location:https://reverse-snake.cloudant.com/highscores/highscores
Non-Authoritative-Reason:HSTS

解释是在CORS机制中,在某些情况下,浏览器首先发送OPTIONS(“预检”)请求以从服务器获取一些功能信息。 PUT请求具有强制预检,而GET请求则没有。该OPTIONS请求无法重定向。

相关问题