1

当我尝试从 Scala Spray 传输请求时出现以下错误

[play-akka.actor.default-dispatcher-14] INFO application - Pipelining chain request
[WARN] [03/19/2015 11:08:49.115] [application-akka.actor.default-dispatcher-2] [akka://application/user/IO-HTTP/group-0/0] Illegal response header: Illegal 'Access-Control-Allow-Origin' header: Unexpected end of input, expected $timesAccess$minusControl$minusAllow$minusOrigin (line 1, pos 1):

^

这是我构建请求的地方:

val pipeline =
  addCredentials(BasicHttpCredentials("API_KEY",
    "API_SECRET")) ~>  sendReceive

val response: Future[HttpResponse] = pipeline(Post(api,notification))
Logger.info("Pipelining chain request")
response

我真的不太了解Access Control Allow Origin。我是否需要在此请求中添加某种标头才能使其正常工作?

4

1 回答 1

1

错误本身意味着Access-Control-Allow-Origin没有正确解析标头(请参阅语法)。这个标头是相当新的,并且允许Cross Origin Resource Sharing。正常示例Access-Control-Allow-Origin(来自此处):

"Access-Control-Allow-Origin" in {
  "Access-Control-Allow-Origin: *" =!= `Access-Control-Allow-Origin`(AllOrigins)
  "Access-Control-Allow-Origin: null" =!= `Access-Control-Allow-Origin`(SomeOrigins(Nil))
  "Access-Control-Allow-Origin: http://spray.io" =!= `Access-Control-Allow-Origin`(SomeOrigins(Seq("http://spray.io")))
}

我猜你可能使用了一些旧版本的 spray,它不支持多个来源,或者可能与this相关。无论如何,只有在请求中指定了标头(这意味着 CORS 启动)时,服务器才会返回带有此标头的响应Origin,因此应该通过Origin从中删除标头来解决问题。

更新:这是您使用的 chain.com API 的错误。如果Origin没有指定 header,它们会返回Access-Control-Allow-Origin:(空字符串)给你,所以它是不可解析的:

> curl -v https://api.chain.com/v2/notifications -X POST
> POST /v2/notifications HTTP/1.1
> User-Agent: curl/7.41.0
> Host: api.chain.com
> Accept: */*
>
< HTTP/1.1 401 Unauthorized
< Access-Control-Allow-Credentials: true
< Access-Control-Allow-Methods: GET,POST,PATCH,PUT,DELETE,OPTIONS,HEAD
< Access-Control-Allow-Origin:
< Content-Type: text/plain; charset=utf-8
< Date: Sun, 22 Mar 2015 01:38:07 GMT
< Strict-Transport-Security: max-age=25920000; includeSubDomains
< Vary: Accept-Encoding
< Www-Authenticate: Basic realm="chain-api"
< X-Content-Type-Options: nosniff
< X-Frame-Options: DENY
< X-Xss-Protection: 1
< Content-Length: 47
< Connection: keep-alive
<
{"code":"CH004","message":"Must authenticate"}

您必须指定一些Origin作为解决方法:

>curl -v https://api.chain.com/v2/notifications -X POST -H "Origin: http://google.com"
> POST /v2/notifications HTTP/1.1
> User-Agent: curl/7.41.0
> Host: api.chain.com
> Accept: */*
> Origin: http://google.com

< HTTP/1.1 401 Unauthorized
< Access-Control-Allow-Credentials: true
< Access-Control-Allow-Methods: GET,POST,PATCH,PUT,DELETE,OPTIONS,HEAD
< Access-Control-Allow-Origin: http://google.com
< Content-Type: text/plain; charset=utf-8
< Date: Sun, 22 Mar 2015 01:39:10 GMT
< Strict-Transport-Security: max-age=25920000; includeSubDomains
< Vary: Accept-Encoding
< Www-Authenticate: Basic realm="chain-api"
< X-Content-Type-Options: nosniff
< X-Frame-Options: DENY
< X-Xss-Protection: 1
< Content-Length: 47
< Connection: keep-alive
于 2015-03-22T00:18:36.507 回答