【问题标题】:HTTP/1.1 401 Unauthorized Error on curl request - herokucurl请求上的HTTP / 1.1 401未经授权的错误-heroku
【发布时间】:2015-01-16 21:16:32
【问题描述】:

我正在尝试通过 curl 向我基于 heroku 的 api 发送请求,但我不断收到此错误:

* Hostname was NOT found in DNS cache
*   Trying 23.21.169.234...
* Connected to helphy-api.herokuapp.com (23.21.169.234) port 80 (#0)
> POST /users/sign_in HTTP/1.1
> User-Agent: curl/7.35.0
> Host: helphy-api.herokuapp.com
> Accept: */*
> Authorization: Bearer d5bd07e4-a1c9-46d2-8d8e-d2a7cbc8501f, Accept: application/json
> Content-Length: 68
> Content-Type: application/x-www-form-urlencoded
> 
* upload completely sent off: 68 out of 68 bytes
< HTTP/1.1 401 Unauthorized 
< Connection: keep-alive
< X-Frame-Options: SAMEORIGIN
< X-Xss-Protection: 1; mode=block
< X-Content-Type-Options: nosniff
< Content-Type: */*; charset=utf-8
< Cache-Control: no-cache
< X-Request-Id: 5b615fce-0674-4302-a9b9-f12cb00db754
< X-Runtime: 0.005328
* Server WEBrick/1.3.1 (Ruby/2.0.0/2014-11-13) is not blacklisted
< Server: WEBrick/1.3.1 (Ruby/2.0.0/2014-11-13)
< Date: Fri, 16 Jan 2015 21:10:12 GMT
< Content-Length: 49
< Via: 1.1 vegur

这是我的 curl 请求:

curl -v -H "Authorization: Bearer $TUTORIAL_KEY, Accept: application/json" -X POST http://helphy-api.herokuapp.com/users/sign_in   -d '{"user": {"email": "xxxxxxx@gmail.com", "password": "xxxxxxx"}}'

更新

这是日志:

2015-01-16T21:43:04.342815+00:00 app[web.1]: Processing by SessionsController#create as */*
2015-01-16T21:43:04.342822+00:00 app[web.1]:   Parameters: {"{\"user\": {\"email\": \"xxxxxx@gmail.com\", \"password\": \"xxxxxxx\"}}"=>nil}
2015-01-16T21:43:04.347678+00:00 app[web.1]: Completed 401 Unauthorized in 5ms
updating...done. Updated to 3.23.2

电子邮件和密码正确且经过检查,顺便说一句。

【问题讨论】:

    标签: ruby-on-rails api curl heroku httprequest


    【解决方案1】:

    您的 -d 参数应该像查询字符串一样采用 x-www-form-urlencoded:

    user[email]=email&user[password]=password
    

    如果您想继续使用 JSON,您必须将 Content-type 标头添加到您的 -H:

    Content-type: application/json
    

    这让服务器知道将您的 POST 数据解释为 JSON 而不是 x-www-form-urlencoded 字符串。这就是为什么在服务器日志中的参数输出如下:

    Parameters: {"{\"user\": {\"email\": \"xxxxxx@gmail.com\", \"password\": \"xxxxxxx\"}}"=>nil}
    

    这只是一个字符串,而不是 JSON,因为服务器不知道您正在发送 JSON,因为您没有包含 Content-type 标头,并且默认情况下服务器假定 POST 数据是 x-www-form-urlencoded字符串。

    【讨论】:

      猜你喜欢
      • 2023-02-23
      • 2021-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-12
      • 2011-03-21
      • 2017-12-20
      相关资源
      最近更新 更多