4

I'm making a get request to the MovieDB API using an axios.create instance. The params object I am attaching which includes the API key is not being sent with the requests.

The requests work fine when using axios.get but not with axios.create.

import axios from "axios";

export default axios.create({
  baseURL: "https://api.themoviedb.org/3",
  params: {
    api_key: MY_API_KEY
  }
});

I am receiving error code 401 Unauthorized.

Mark
  • 41
  • 3
  • I don't think it's a syntax issue. 401 means not allowed to access the resource. You probably need a token to pass in the API as well – Adeel Imran Jun 23 '19 at 21:33
  • Possible duplicate of [Attach Authorization header for all axios requests](https://stackoverflow.com/questions/43051291/attach-authorization-header-for-all-axios-requests) – Bhavay Anand Jun 23 '19 at 21:52

1 Answers1

1

You can use paramsSerializer for this:

export const client = Axios.create({
    baseURL: process.env.API_URL,
    paramsSerializer: (params) => {
        const serializedParams = qs.stringify(params, {arrayFormat: 'repeat'});
        return `${serializedParams}&APPID=${process.env.API_KEY}`;
    }
});

And sure you need to install qs before implementing this:

npm i qs

Sergio Ivanuzzo
  • 1,820
  • 4
  • 29
  • 59