我有一个运行中的长沙发服务器,并且尝试从端口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 )


当我尝试在url中传递凭据时,似乎我的凭据已被删除,并且在使用会话时cookie没有发送到服务器。

最佳答案

您的请求由于Same-Origin Policy而失败,因为您通过AJAX请求使用其他端口(而不是80)发送了url。您需要正确设置CORS才能使请求成功。

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

08-18 03:50
查看更多