简体   繁体   English

在 axios 中返回 object 而不是 null

[英]Return an object instead of null in axios

Question: Why the Authorization has value is Object instead of null?问题:为什么授权的值为 Object 而不是 null? When the function USER_TOKEN.get() return value is null.当 function USER_TOKEN.get() 返回值为 null 时。

I have a function name is callApi like this我有一个 function 名称是这样的 callApi

export async function callApi(endpoint, method = "get", body) {
  try {
    const res = await axios({
      method: method,
      url: endpoint,
      data: body,
      headers: {
        Authorization: USER_TOKEN.get()
      }
    });
    if (res && res.data && res.data.success === true) {
      return res.data.payload;
    }
    return Promise.reject(Error("Call api failed"));
  } catch (error) {
    throw error;
  }
}

This is my function USER_TOKEN.这是我的 function USER_TOKEN。 And USER_TOKEN.get() just get value from locaStorage item 'userToken'而 USER_TOKEN.get() 只是从 locaStorage 项目 'userToken' 中获取价值

export const USER_TOKEN = {
  get: () => localStorage.getItem('userToken'),
  set: (newValue) => {
    localStorage.setItem('userToken', `Bearer ${newValue}`);
  },
  delete: () => localStorage.removeItem('userToken'),
};

The result I got is the image below enter image description here我得到的结果是下面的图像 在此处输入图像描述

My expectation is the header's element Authorization have value is null instead of Object like the image above.我的期望是标题的元素 Authorization 的值为 null 而不是 Object ,如上图。

Please help me explain this issue.请帮我解释一下这个问题。 Or can you give some keyword to research?或者你能给出一些关键词来研究吗? Thank you!谢谢!

Seems Axios does some object checks on each header and some fancy, null-safe stringifying which is what's converting your null into [object Object] . Seems Axios does some object checks on each header and some fancy, null-safe stringifying which is what's converting your null into [object Object] .

I'd say the best thing to do is programmatically add the header, eg我想说最好的办法是以编程方式添加 header,例如

const authorization = USER_TOKEN.get()
const headers = authorization ? { authorization } : {}
const res = axios({
  method,
  headers,
  url: endpoint,
  // etc
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM