簡體   English   中英

Rails API 空請求標頭

[英]Rails API empty request headers

從 javascript 向 rails 發送請求並提供帶有令牌的Authorization標頭總是在我的 rails API 上顯示為空標頭。

我的所有 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

結尾

像這樣在 javascript 端執行我的 fetch 請求:

  fetch(`/api/clients?page=${page}`, {
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      'Authorization': AUTH_TOKEN
    },
    credentials: 'same-origin',
  })

request.headers獲取值Authorization總是為零。

任何人都知道可能會出什么問題?

由於您使用的是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) {
  ...
});

我在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);
      });

正確方法:postput等請求相比, get請求中的參數和標頭的傳遞方式不同。 Axios 在第二個參數中獲取整個配置,而不是配置對象列表。 將參數放在配置中,並將整個對象作為第二個參數傳遞

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM