简体   繁体   中英

Why is Axios not using the Content-Type header and converting the request method to GET when PATCHing to a specific URL?

I have inherited a codebase using Axios, and I am otherwise unfamiliar with the library. This is a Node application, and I'm attempting to send a PATCH request to a third party API. Axios is configured using the following:

const axios = require('axios').create({
  baseURL: process.env.API_URL,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  },
  auth: {
    username: process.env.API_USER,
    password: process.env.API_PW,
  },
});

I then try to make the following PATCH request:

const data = {
    fields: {
      field_a: 'yes',
      field_b: 'no',    
    },
  };

  try {
    const res = await axios.patch(`/user/${user.id}`, data, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    return res;
  } catch (err){
    console.error(err);
  }

From what I can see I'm just redefining the Content-Type header when making the patch call, but that was just an attempt to figure this out. It doesn't work either way. What I see in the response object's config property is the following (most of it is excluded):

{
  headers: {
    Accept: "application/json"
    User-Agent: "axios/0.19.0"
  },
  method: 'patch',
}

Looking at the request property of the same response object I see that the method there is listed as "GET" with the Content-Type header also not listed there. It appears as though the Content-Type header is being stripped and the method is being changed to GET.

If I change nothing but the URL destination to /userWRONGPATH/${user.id} I receive, as expected, a 404 response, but the response object's config data includes this:

{
  headers: {
    Accept: "application/json"
    Content-Length: 105
    Content-Type: "application/json"
    User-Agent: "axios/0.19.0"
  }
}

The response object's request method is now the expected 'PATCH'. I am unsure why the patch method would work for other paths if that is in fact what is happening here.

Hello I think that the problem could be related of send the header again in Axios you define a config and that is added to all the requests.

This is an example that I use to order the project with axios.

// Axios custom config
const axiosInstance = axios.create({
  baseURL: urlBase,
  // timeout: 1000,
  headers: { 'Content-type': 'application/json' },
});


export const apiPatchRequest = (url, id, obj) => (
  axiosInstance.patch(`${url}/${id}`, obj)
);

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