params object (API key) not being sent with axios.create

Viewed 1242

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.

1 Answers

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

Related