jquery ajax基本auth节点表达

时间:2014-11-17 22:07:27

标签: jquery ajax node.js express basic-authentication

我希望ajax通过基本身份验证,将返回401状态

的客户端

使用coffeescript

使用jquery.base64.js

$.ajax
  url : "http://example.com/"
  type: "GET"
  dataType: "text"
  crossDomain: true
  beforeSend: (xhr)->
    credentials = $.base64.encode("user:pass")
    xhr.withCredentials = true
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
    xhr.setRequestHeader("Authorization", "Basic " + credentials)

.always (result, textStatus, jqXHR) =>
  if textStatus == "success"
    console.log "success"

服务器

使用coffeescript

使用node.js express

router.use (req, res, next)->
  res.header "Access-Control-Allow-Origin", "http://client.com/"
  res.header "Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, HEAD, OPTIONS"
  res.header "Access-Allow-Control-Credentials", "true"
  res.header "Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization"
  next()

router.use basicAuth('user', 'pass')

router.get "/", (req, res)=>
  res.json 200, {
    status_code: 0
  }

以下是我尝试实际发送时的结果

请求

Remote Address:example.com
Request URL:http://example.com/
Request Method:OPTIONS
Status Code:401 Unauthorized
Request Headers
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Access-Control-Request-Headers:accept, authorization
Access-Control-Request-Method:GET
Connection:keep-alive
Host:example.com
Origin:http://client.com
Referer:http://client.com/
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2219.0 Safari/537.36

响应

Response Headers
Access-Allow-Control-Credentials:true
Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept, Authorization
Access-Control-Allow-Methods:GET, PUT, POST, DELETE, HEAD, OPTIONS
Access-Control-Allow-Origin:http://client.com
Connection:keep-alive
Date:Mon, 17 Nov 2014 21:30:08 GMT
Transfer-Encoding:chunked
WWW-Authenticate:Basic realm="Authorization Required"
X-Powered-By:Express

在本地环境中运行 为什么返回401状态

0 个答案:

没有答案