如何在 axios 中设置标题和选项?

IT技术 javascript post axios
2021-01-18 22:36:49

我使用 Axios 执行这样的 HTTP 帖子:

import axios from 'axios'
params = {'HTTP_CONTENT_LANGUAGE': self.language}
headers = {'header1': value}
axios.post(url, params, headers)

这个对吗?或者我应该这样做:

axios.post(url, params: params, headers: headers)
6个回答

做这件事有很多种方法:

  • 对于单个请求:

    let config = {
      headers: {
        header1: value,
      }
    }
    
    let data = {
      'HTTP_CONTENT_LANGUAGE': self.language
    }
    
    axios.post(URL, data, config).then(...)
    
  • 设置默认全局配置:

    axios.defaults.headers.post['header1'] = 'value' // for POST requests
    axios.defaults.headers.common['header1'] = 'value' // for all requests
    
  • 要在 axios 实例上设置为默认值:

    let instance = axios.create({
      headers: {
        post: {        // can be common or any other method
          header1: 'value1'
        }
      }
    })
    
    //- or after instance has been created
    instance.defaults.headers.post['header1'] = 'value'
    
    //- or before a request is made
    // using Interceptors
    instance.interceptors.request.use(config => {
      config.headers.post['header1'] = 'value';
      return config;
    });
    

您可以发送带有 Headers 的 get 请求(例如使用 jwt 进行身份验证):

axios.get('https://example.com/getSomething', {
 headers: {
   Authorization: 'Bearer ' + token //the token is a variable which holds the token
 }
})

您也可以发送post请求。

axios.post('https://example.com/postSomething', {
 email: varEmail, //varEmail is a variable which holds the email
 password: varPassword
},
{
  headers: {
    Authorization: 'Bearer ' + varToken
  }
})

我这样做的方法是设置这样的请求:

 axios({
  method: 'post', //you can set what request you want to be
  url: 'https://example.com/request',
  data: {id: varID},
  headers: {
    Authorization: 'Bearer ' + varToken
  }
})
您的第二个帖子请求没有提供特定的标题,您可以编辑它的完整示例吗?
2021-03-14 22:36:49
您是否必须遵循“授权:‘承载’+令牌”的标准,或者您可以执行诸如 Auth: token 之类的操作吗?我没有使用 auth0 api,而是在 node 中做我自己的,抱歉,如果 jwt 和一般安全性的新问题是愚蠢的
2021-04-03 22:36:49
通过data在interceptors.request => 中使用,它将从我们正在使用的特定调用中覆盖您的实际正文部分。所以在这种情况下不使用。
2021-04-04 22:36:49

axios.post('url', {"body":data}, {
    headers: {
    'Content-Type': 'application/json'
    }
  }
)

我很困惑header是用单数还是复数声明。从你的回答来看,这对我有帮助。
2021-03-15 22:36:49

您可以将配置对象传递给 axios,例如:

axios({
  method: 'post',
  url: '....',
  params: {'HTTP_CONTENT_LANGUAGE': self.language},
  headers: {'header1': value}
})

这是正确的方法:-

axios.post('url', {"body":data}, {
    headers: {
    'Content-Type': 'application/json'
    }
  }
)