简体   繁体   中英

What config does in the axios.get?

Can someone help me understand why it should have the config for this? What was headers or authorization does? Why should I put it as a second parameter?

dispatch({ type: 'FETCH_REQUEST' });
    let config = {
      headers: { authorization: `Bearer ${userInfo.token}` },
    };
    //Fetching the data from the backend
    const { data } = await axios.get(`/api/orders/${orderId}`, config);

The header is essentially the header of the HTTP request . You need it for special config like authentication key, XSSR token, and other special config which you can read more in that link. The authorization is a authorization token. This is usually the JWT token that you got from the server when you've finished the authentication process. You can read more on the JWT authentication process here . Once you got the authorization token in your header of your request and send it to your server, your server will read in this token, deserialize it to get the data and determine if your HTTP request are valid and return the data. If your token is not valid, the server will throw an 403 (Unauthorize) error.

axios() has a whole number of ways you can specify the request you want.

For example, you can specify just a config object:

// Send a POST request
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

Where the config object contains the method, url and other necessary options.

For all other types of requests, the config object is optional and is only needed if you need to specify some argument other than the URL or the data to send.

For example, with axios.get() , you can use either axios.get(someUrl) or axios.get(someUrl, config) . The config object can contain all the options listed here in the doc. Among those options are custom headers, data to append to the URL (for a GET request), options for timeout, sending of credentials, basic auth, progress callbacks, etc....

All these options in the config object are optional. You only need to specify the ones that your particular request requires.


In the code example you show in your question:

let config = {
  headers: { authorization: `Bearer ${userInfo.token}` },
};
//Fetching the data from the backend
const { data } = await axios.get(`/api/orders/${orderId}`, config);

This is specifying a custom header for the request that contains an authorization token that is presumably required by the server for this particular type of request so that in the headers of the http request, it will add something like this:

Authorization: Bearer someTokenValueHere

You can read about the authorization header here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM