为什么axios忽略头文件?

cgyqldqp  于 2023-02-22  发布在  iOS
关注(0)|答案(3)|浏览(112)

axios忽略以下代码中的头:

static async likePost(jwt: string | null){

    const response = await axios.post(`http://localhost:4000/api/feed/like`, {
        headers: {
            authorization: 'Bearer ' + jwt
        }
    });

    return response
}

但在代码中添加标题:

static async getProfileByJWT(jwt: string| null) {

    const response = await axios.get(`http://localhost:4000/api/profile`, {
        headers: {
            authorization: 'Bearer ' + jwt
        }
    });

    return response.data.candidate
}

我需要做什么来解决这个问题?
我试着添加默认的标题,甚至请求,但它没有工作.

vcudknz3

vcudknz31#

post接受3个参数axios.post(url[, data[, config]]),因此调用应如下所示

const response = await axios.post(
  `http://localhost:4000/api/feed/like`, 
  {/* data you want to post goes here */},  
  {
        headers: {
            authorization: 'Bearer ' + jwt
        }
   }
);
f8rj6qna

f8rj6qna2#

要为所有请求添加默认标头(config_defaults),您可以设置它们:

// Set config defaults when creating the instance
const instance = axios.create({
  baseURL: 'https://api.example.com'
});

// Alter defaults after instance has been created

// Alter default for all requests
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

// Alter defaults only for post request
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

// Alter defaults only for get request
instance.defaults.headers.get['x-rapid-api-key'] = API_KEY;
zf9nrax1

zf9nrax13#

要发送带标头的Axios POST请求,您需要使用标头选项。使用axios.post()时,第一个参数是URL,第二个参数是请求正文,第三个参数是选项。例如,下面是如何设置HTTP POST请求的授权标头。

const res = await axios.post('https://httpbin.org/post', { hello: 'world' }, {
  headers: {
    'authorization': 'Bearer ' + jwt
  }
});

在您的情况下,您没有提供数据。在发布请求中,您需要提供正文。如果您没有正文数据,您需要保留为空。

相关问题