What is axios.defaults.headers.post 'content-type' = 'application/json'

huangapple go评论80阅读模式
英文:

What is axios.defaults.headers.post 'content-type' = 'application/json'

问题

我是新手学习React,我很难理解axios.defaults.headers.post 'content-type' = 'application/json'是什么意思。

我已经进行了大量搜索,但没有找到合适的答案来解释它的含义。

英文:

I am new to react and and i am finding difficult to understand what axios.defaults.headers.post 'content-type' = 'application/json' means.

I had search a lot but not find suitable answers what does it means.

答案1

得分: 5

设置全局默认标头。请查看全局axios默认值

通常,您应该按以下方式发出请求:

import qs from 'qs';
const data = { 'bar': 123 };
const options = {
  method: 'POST',
  headers: { 'content-type': 'application/x-www-form-urlencoded' },
  data: qs.stringify(data),
  url,
};
axios(options);

如果您的大多数请求将具有Content-Type=application/x-www-form-urlencoded标头,您可以设置默认标头:

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

然后,您可以从请求选项中删除标头行。

英文:

It sets global default headers. Please check Global axios defaults

Normally you should make a request as below:

import qs from 'qs';
const data = { 'bar': 123 };
const options = {
  method: 'POST',
  headers: { 'content-type': 'application/x-www-form-urlencoded' },
  data: qs.stringify(data),
  url,
};
axios(options);

If most of your request will have Content-Type=application/x-www-form-urlencoded header, you can set default header with:

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

And you can delete headers line from your request options.

答案2

得分: -1

基本上,它用于在 componentDidMount 中从 API 获取数据,或者如果你使用 GraphQL 获取数据,那么在解析器函数中也必须使用 'content-type' = 'application/json'。
'content-type' = 'application/json' 意味着你的内容必须是 JSON 格式。

var options = {
    "url": "",
    "method": "POST",
    "headers": {
        "content-type": "application/json",
        "cache-control": 'no-cache'
    },
    qs: {
        limit: limit,
        offset: offset
    }
}
英文:

It is basically using for fetching data from API in componentDidMount or if you using grapghQLfor fetching data then that time also you have to use 'content-type' = 'application/json' in resolver function.
'content-type' = 'application/json' that means your content must be in json format.

var options = {
    "url":"",
    "method": "POST",
        "headers":{
            "content-type":"application/json",
            "cache-control":'no-cache'
        },
        qs:{
            limit : limit 
            offset : offset
        }
    }

</details>



huangapple
  • 本文由 发表于 2020年1月6日 18:40:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/59610614.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定