如何在每个 http 调用中为默认请求标头创建 axios 配置? [英] How do I create configuration for axios for default request headers in every http call?

查看:19
本文介绍了如何在每个 http 调用中为默认请求标头创建 axios 配置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

https://github.com/MrFiniOrg/AxiosQuestion

我想设置我的项目,这样我就不必在每个 http 调用中指定相同的请求标头.

I would like to have my project setup so that I do not have to specify the same request header in every http call.

我已经在网上搜索过这个,但在我的项目中我没能做到这一点.

I have searched this online but I have not been able to accomplish this in my project.

请有人帮助我解决我遇到的这个问题.我是 react 和 axios 的新手,我不确定如何配置它.

Would someone please assist me in resolving this issue I am having. I am new to react and axios and I am not sure how to configure this.

我的项目似乎正在执行此操作,但它发送了 2 次请求.一个有标题,一个没有.

My project seems to be doing this but it is sending the request 2 times. One with the header and one without.

我的axios调用可以在app.js类组件中找到

My axios call can be found in the app.js class component

推荐答案

您可以指定将应用于每个请求的配置默认值.

You can specify config defaults that will be applied to every request.

全局 axios 默认值

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

有关更多具体信息,请访问他们的文档.

For more specific info, please visit their docs.

更新:

你可以通过两种方式做到:

1. 在您的 index.js 文件 [意味着顶级又名根"文件] 中,您可以配置您的请求/响应 方法.像这样:

1. In your index.js file [meaning the top-level aka 'root' file] you can configure your request/ response methods. Something like this:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import axios from 'axios';

axios.defaults.baseURL = 'https://jsonplaceholder.typicode.com';
axios.defaults.headers.common['Authorization'] = 'AUTH TOKEN';
axios.defaults.headers.post['Content-Type'] = 'application/json';

axios.interceptors.request.use(request => {
    console.log(request);
    // Edit request config
    return request;
}, error => {
    console.log(error);
    return Promise.reject(error);
});

axios.interceptors.response.use(response => {
    console.log(response);
    // Edit response config
    return response;
}, error => {
    console.log(error);
    return Promise.reject(error);
});

ReactDOM.render( <App />, document.getElementById( 'root' ) );
registerServiceWorker();


2. 或者您可以创建一个新文件,准确地说是 axios.js 文件的一个新实例,然后在您的组件中单独导入配置可能需要它们.您可以命名它,例如 axiosConfig.js,并将您的特定配置放入其中.像这样:


2. Or you can create a new file, a new instance of your axios.js file to be precise, and import the configurations separately in your components where you might need them. You could name it, eg axiosConfig.js, and put your specific configs inside of it. Something like this:

axiosConfig.js

// First we need to import axios.js
import axios from 'axios';
// Next we make an 'instance' of it
const instance = axios.create({
// .. where we make our configurations
    baseURL: 'https://api.example.com'
});

// Where you would set stuff like your 'Authorization' header, etc ...
instance.defaults.headers.common['Authorization'] = 'AUTH TOKEN FROM INSTANCE';

// Also add/ configure interceptors && all the other cool stuff

instance.interceptors.request...

export default instance;

之后,您可以将此文件导入到需要它的组件中并使用它代替之前的 Axios [node_modules] 导入,如下所示:

After that you would import this file to components that need it and use it instead of the previous Axios [node_modules] import, like this:

Example.js

import React, { Component } from 'react';
// import axios from 'axios'; We don't need this anymore
import axiosConfig from '../../axiosConfig'; // But instead our new configured version :)

class Example extends Component {
    state = {
        data: [],
        error: false
    }

    componentDidMount () {
        // We could name (import) it as axios instead, but this makes more sense here ... 
        axiosConfig.get('/posts' )
            .then(response => {
                   this.setState({data: response});
                });
            })
            .catch(error => {
                this.setState({error: true});
            });
    }

注意:您可以根据需要组合这两种方法,但请记住,在您的 configAxios.js 文件中进行的配置将覆盖那些在你的 index.js 文件中制作 [如果它们是相同的配置,那就是 :) ]

NOTE: You can combine these two methods as needed, but remember that the configurations made in your configAxios.js file will overwrite those made in your index.js file [if they are the same configurations, that is :) ]

这篇关于如何在每个 http 调用中为默认请求标头创建 axios 配置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆