簡體   English   中英

如何修改這個 axios 對象,以便我可以在各種標題之間進行選擇?

[英]How to modify this axios object so I can choose between various headers?

我目前有以下 axios 對象

    import axios from 'axios';
import constants from '../constants.js';
import Cookies from 'js-cookie';

const API = axios.create({
  baseURL: `${constants.urlBackend}`,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  },
});

API.interceptors.request.use(
  config => {
    var accesstoken = Cookies.get('accesstoken');

    if (accesstoken) {
      config.headers.Authorization = `Bearer ${accesstoken}`;
    } else {
      delete API.defaults.headers.common.Authorization;
    }
    return config;
  },

  error => Promise.reject(error)
);

export default API;

例如,我使用如下

API.get(constants.urlBackend + "/status/ftp/Server3")
        .then((response) => {
            if (response.status === 200) {
                this.setState({ sonServerThreeStatus: true });
            } else {
                this.setState({ sonServerThreeStatus: false });
            }
        })
        .catch((error) => {
            this.setState({ sonServerThreeStatus: false })
        });

重點是,到目前為止,我使用該對象使用的所有請求都具有 application/json 內容標頭,但是我面臨一個問題,並且有些需要

headers: {
                 'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
             }

所以我不知道如何在各種標題之間觸發,或者如何讓該對象在多個選項之間進行選擇以及如何調用它。

解決了,我從對象中刪除了標題,現在我只是在啟動對象時指定它們

 API.post(constants.urlBackend + "/register", qs.stringify({ email, password }), {
            'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
        }).

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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