我正在学习Ruby编程,并且正在构建一个API测试项目。我有一个特定站点的请求,并且正在使用Faraday gem。 这是我的代码:
conn = Faraday.new
f_response = conn.post do |req|
req.url 'https://api.abcxyz.vn/v2/tokens'
req.headers['Content-Type'] = 'application/json'
req.body = '{"email": "xxx@gmail.com","password": "abc123","grant_type": "password"}'
end
请求正常,我得到了成功的代码201。
但是我不了解req.headers['Content-Type'] = 'application/json'
的格式。它是哈希还是数组。因为如果我按以下方式替换代码:
request_headers = {"Content-Type" => "application/json"}
conn = Faraday.new
f_response = conn.post do |req|
req.url 'https://api.abcxyz.vn/v2/tokens'
req.headers = request_headers
req.body = '{"email": "xxx@gmail.com","password": "abc123","grant_type": "password"}'
end
结果404错误代码。不好意思,请您帮我解决这个问题。 另外,我还有另一个API,要求在标头字段中附加“ X-Access-Token”。 如何将其输入有效载荷中。
答案 0 :(得分:0)
req.headers是一个哈希,但是通过使用req.headers =
,您将清除Faraday自动设置的所有标题,例如'User-Agent'。要添加新的标题,请执行与“ Content-Type”相同的操作:
conn = Faraday.new
f_response = conn.post do |req|
req.url 'https://api.abcxyz.vn/v2/tokens'
req.headers['Content-Type'] = 'application/json'
req.headers['X-Access-Token'] = 'x-access-token-goes-here'
req.body = '{"email": "xxx@gmail.com","password": "abc123","grant_type": "password"}'
end