根据Javascript中的条件设置标题

时间:2019-07-09 08:14:04

标签: javascript reactjs axios

我正在开发一个React应用程序,在该应用程序中,我根据令牌的存在情况检查本地存储中令牌的可用性,我需要设置标头。

我尝试通过在循环外初始化JavaScript对象,然后在if else条件下设置标头来实现。

getAllTopics() {
       const token = localStorage.getItem('authKey');
       var config = {};

       if(token){
         const URL = API_URL + `api/get-home-ideas-auth`;
          var config = {
           'Accept' : 'application/json',
           'Authorization' : `Bearer ` + token
       }

       } else {
         const URL = API_URL + `api/get-home-ideas`;
            var config = {
           'Accept' : 'application/json'
       }

       }
         axios.get(URL, {headers : config})
           .then(res => {
             if (res.data && res.data.status === 1) {
               const topics = res.data.data;
               console.log(topics);
               this.setState({ topics: topics, showloader:false});
             } 

           })
           .catch(e => {console.error(e); throw e;});
       }

我遇到错误Cannot GET /function URL()[nativecode]

3 个答案:

答案 0 :(得分:1)

这是一个范围界定问题,问题在于您在 if-else块中初始化了一个新的config变量,而不是引用范围之外已经定义的变量。在私有 if-else 范围之外无法访问新的config变量。外部config从未真正更新过。

只需引用原始的config即可,

getAllTopics() {
   const token = localStorage.getItem('authKey');
   var config = {};
   var URL = '';
   if(token){
     URL = API_URL + "api/get-home-ideas-auth";
      config = {
         'Accept' : 'application/json',
         'Authorization' : `Bearer ${token}`
      }

   } else {
     URL = API_URL + "api/get-home-ideas";
        config = {
          'Accept' : 'application/json'
        }
   }

     axios.get(URL, {headers : config})
       .then(res => {
         if (res.data && res.data.status === 1) {
           const topics = res.data.data;
           console.log(topics);
           this.setState({ topics: topics, showloader:false});
         } 

       })
       .catch(e => {console.error(e); throw e;});
   }

答案 1 :(得分:0)

getAllTopics() {
   const token = localStorage.getItem('authKey');
   const URL = API_URL + `api/get-home-ideas-auth`;
   var config = {
   'Accept' : 'application/json',
   ...(token && {'Authorization' : `Bearer ` + token})
  }

     axios.get(URL, {headers : config})
       .then(res => {
         if (res.data && res.data.status === 1) {
           const topics = res.data.data;
           console.log(topics);
           this.setState({ topics: topics, showloader:false});
         } 

       })
       .catch(e => {console.error(e); throw e;});
   } 

答案 2 :(得分:0)

尽管已经回答,但最干净的方法是通过拦截器

/**
 * Create an Axios Client with defaults
 */
const client = axios.create({
  baseURL: API.BASE_URL,
});

/*
* Request interceptor
* Useful for refreshing token before to make a new request and get 401 responses
*/
client.interceptors.request.use(
  config => {
    const originalRequest = _.cloneDeep(config);
    // Using lodash _.set() we avoid undefined keys in path
    _.set(originalRequest, 'headers.Authorization', getAuth());
    return originalRequest;
  },
  err => Promise.reject(err),
);