[英]Rails API empty request headers
Sending request from javascript to rails and providing the Authorization
header with a token always shows up as empty headers on my rails API.从 javascript 向 rails 发送请求并提供带有令牌的Authorization
标头总是在我的 rails API 上显示为空标头。
I have the follow piece of base code for all my API controllers:我的所有 API 控制器都有以下基本代码:
module Api
class BaseController < ActionController::API
before_action :require_login
private
def require_login
unless signed_in?
head :unauthorized
end
end
def signed_in?
current_user.present?
end
def current_user
if request.headers['Authorization'].present?
User.find_by(token: request.headers['Authorization'])
else
nil
end
end
end
end结尾
Doing my fetch request on javascript side like this:像这样在 javascript 端执行我的 fetch 请求:
fetch(`/api/clients?page=${page}`, {
headers: {
Accept: "application/json",
"Content-Type": "application/json",
'Authorization': AUTH_TOKEN
},
credentials: 'same-origin',
})
Fetching the value Authorization
from request.headers
always comes up as nil.从request.headers
获取值Authorization
总是为零。
Anyone knows what might be going wrong?任何人都知道可能会出什么问题?
Since you're using the Fetch()
library, you can use the new Request()
object which helps you customize your configurations.由于您使用的是Fetch()
库,因此您可以使用new Request()
对象来帮助您自定义配置。
// https://developer.mozilla.org/en-US/docs/Web/API/Request/Request
var myHeaders = new Headers({
"Content-Type": "application/json",
'Authorization': AUTH_TOKEN
});
var myInit = { method: 'GET',
headers: myHeaders,
mode: 'cors',
cache: 'default' };
var myRequest = new Request(`/api/clients?page=${page}, myInit);
fetch(myRequest).then(function(response) {
...
});
I had the same issue with Axios
and it turns out I was using a get
request with headers and params wrongly .我在Axios
遇到了同样的问题,结果我错误地使用了带有标头和参数的get
请求。
const params = { id: "ghjfsd7634" };
const headers = {
headers: {
"Content-Type": "application/json",
Authorization: token,
},
};
axios
.get(url, params, headers)
.then(function foo(response) {
handleResponse(response.data);
})
.catch(function foo(error) {
console.log("GET Resource Error");
console.log(error);
});
Correct way: Params and headers in get
requests are passed differently compared to post
, put
etc. requests.正确方法:与post
、 put
等请求相比, get
请求中的参数和标头的传递方式不同。 Axios takes the entire config in the second argument, not a list of config objects. Axios 在第二个参数中获取整个配置,而不是配置对象列表。 Put the params inside the config, and pass the entire object as the second argument :将参数放在配置中,并将整个对象作为第二个参数传递:
const params = { id: "ghjfsd7634" };
const headers = {
"Content-Type": "application/json",
Authorization: token,
};
const config = { headers, params };
await axios
.get(url, config)
.then(function foo(response) {
handleResponse(response.data);
})
.catch(function foo(error) {
console.log("GET Resource Error");
console.log(error);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.