Curl

不確定如何使用 curl 獲取使用標頭中的參數

  • January 31, 2018

按照這個例子。

當我這樣向網站發送命令時,它會起作用並返回一個令牌:

[idf@xxxx ~]$  curl -d "name=Ivan&email=idf@xxxcom&password=secret" -H "Content-Type: application/x-www-form-urlencoded" -X POST localhost:3002/api/auth/register 

{"auth":true,"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVhNzIwYzZkYzI2ZjNlNzRhMjZhODg1YiIsImlhdCI6MTUxNzQyMzcyNSwiZXhwIjoxNTE3NTEwMTI1fQ.W_lffqIlGh21UD2o4Sqd6mISrAC6PKv6swTQvQV1IfU"}

[idf@xxxx ~]$ 

然後我應該將此令牌用於GET有關使用者的一些資訊。我試過這個:

[idf@xxx ~]$  curl -v -d "x-access-token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVhNzIwODlhNGZkZTViNzM5N2M1YjQ5YiIsImlhdCI6MTUxNzQyMjc0NiwiZXhwIjoxNTE3NTA5MTQ2fQ.7a5KPDvB-13KYrAfkBa_2-d3XKru1J1OkxWlofnxhFw" -H "Content-Type: application/x-www-form-urlencoded" -X GET localhost:3002/api/auth/me
* About to connect() to localhost port 3002 (#0)
*   Trying ::1...
* Connected to localhost (::1) port 3002 (#0)
> GET /api/auth/me HTTP/1.1
> User-Agent: curl/7.29.0
> Host: localhost:3002
> Accept: */*
> Content-Type: application/x-www-form-urlencoded
> Content-Length: 186
> 
* upload completely sent off: 186 out of 186 bytes
< HTTP/1.1 403 Forbidden
< X-Powered-By: Express
< Content-Type: application/json; charset=utf-8
< Content-Length: 45
< ETag: W/"2d-vj/ohbytTg+R1uXxU34fCnv4o0o"
< Date: Wed, 31 Jan 2018 18:29:45 GMT
< Connection: keep-alive
< 
* Connection #0 to host localhost left intact
[idf@xxxx ~]$ 

但它回來了:

{"auth":false,"message":"No token provided."}

[idf@xxxx ~]$

我幾乎可以肯定使用curl不正確的方式將參數傳遞給GET. curl GET形成字元串的正確方法是什麼?

HTTP GET 請求參數在 URL 中傳遞,如下所示:

http://example.com/path/file?argument=value

因此,在您的情況下,Curl 命令行將是:

curl http://localhost:3002/api/auth/me?x-access-token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVhNzIwODlhNGZkZTViNzM5N2M1YjQ5YiIsImlhdCI6MTUxNzQyMjc0NiwiZXhwIjoxNTE3NTA5MTQ2fQ.7a5KPDvB-13KYrAfkBa_2-d3XKru1J1OkxWlofnxhFw

假設 API 確實應該通過 GET 請求和查詢參數工作,這應該可以工作。

但是,該x-access-token參數聽起來更像是一個 HTTP 標頭,然後您需要使用以下命令行:

curl -H "x-access-token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVhNzIwODlhNGZkZTViNzM5N2M1YjQ5YiIsImlhdCI6MTUxNzQyMjc0NiwiZXhwIjoxNTE3NTA5MTQ2fQ.7a5KPDvB-13KYrAfkBa_2-d3XKru1J1OkxWlofnxhFw" http://localhost:3002/api/auth/me

引用自:https://serverfault.com/questions/895048