难以通过CouchDB进行身份验证

时间:2014-05-15 15:07:34

标签: javascript jquery ajax couchdb

我有一台沙发服务器正在运行,我正在尝试从端口80提供的Web应用程序访问它。我很难进行身份验证。

我用来测试的代码是:

var host = 'http://localhost:5984'
var url = host + "/wells/"
var username = 'will'
var password = 'secret'

// Succeeds
$.post(
  host + "/_session",
  { name: username, password: password },
  function() {
    console.log( 'cookie', document.cookie ) // doesn't include AuthSession
    $.get( url ) // Fails 401 unauthorized
  }
)

var hostParts = host.split( '://' )
var hostWithAuth = hostParts[1] + "://" + username + ":" + password + "@" + hostParts[2]
$.get( hostWithAuth ) // Fails unauthorized, credentials removed from url

// Fails unauthorized
$.ajax( {
  url: url,
  username: username,
  password: password,
  success: function() {
    console.log( arguments )
  },
  xhrFields: { withCredentials: true },
  headers: {
    Authorization: "Basic " + btoa( username + ":" + password )
  }
} )

// Fails unauthorized
var xmlHttp = new XMLHttpRequest()
xmlHttp.open( 'GET', url, false, username, password )
xmlHttp.send( null )
console.log( xmlHttp.responseText )

当我尝试在网址中传递凭据时,我的凭据似乎被移除,并且在使用会话时cookie未被发送到服务器。

1 个答案:

答案 0 :(得分:1)

您的请求因Same-Origin Policy而失败,因为您使用不同的端口(而非80)向url发出了AJAX请求。您需要正确设置CORS才能让您的请求成功。

P.S。为什么不使用jquery.couch.js作为客户端库而不是自己的$ .ajax调用?它处理许多有用的位并提供更好的API。

相关问题