XMLHttpRequest 服务器响应状态为 405(方法不允许)

XMLHttpRequest server responded with a status of 405 (Method Not Allowed)

我正在使用此 HTTP POST 请求代码将 json 数据发送到 Couchbase bucket/document。我不知道为什么它会抛出错误 "XMLHttpRequest send Failed to load resource: the server responded with a status of 405 (Method Not Allowed)"

当我测试它时,它通过 Postman 工作正常。

var params = {
    "EmpID":"567453",
    "EmpAddress": "XX",
    "EmpAccount": "89723",
    "EmpName": "user1953977",
    "EmpType": "DEV"
}
var xhr = new XMLHttpRequest();
var url = "http://xxxx:PORT/xxxx/xxx/xxx/docs/docs/firstdoc/"; // Couchbase document url
xhr.open("POST", url, true);

xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Accept", "application/json" );
xhr.setRequestHeader("Authorization", "Basic XXXXXXXXXXXXXXXXXX");
xhr.setRequestHeader("Cache-Control", "no-cache");

var data = JSON.stringify(params);
xhr.send(data)

谁能告诉我问题出在哪里?有办法解决吗?

我很确定您正在做的是从浏览器向 Couchbase 服务器发出 POST 请求。您收到的 405 错误可能是由于 CORS。在 Couchbase Server 中不能关闭 CORS(我猜除非你自己分叉和编译)。 Couchbase Server 并非设计为像这样直接从浏览器访问。

部分选项:

  1. Couchbase 服务器位于 API 后面,您可以使用您选择的 SDK(节点、Java、.NET 等)在那里与 Couchbase 交互。

  2. 在 Couchbase 前面使用 Sync Gateway,它有一个 API 允许您启用 CORS(参见 Sync Gateway Public REST API documentation)。

  3. 在浏览器中关闭同源策略 (like in Chrome),但这对大多数应用程序来说通常不实用,因为您需要每个用户都关闭 CORS。