Nyholm / psr7

A super lightweight PSR-7 implementation
MIT License
1.15k stars 75 forks source link

Axios get request gives [AxiosError:Network Error] & Error: header name must be a non-empty string #208

Closed OmarZakariia closed 1 year ago

OmarZakariia commented 1 year ago

this is the function I use

export async function getDishes() {

const url = DishesAuthURL;

const userToken = newUser.getToken();

const authStr = "Bearer ".concat(userToken); console.log("πŸš€ ~ file: menu.js:108 ~ getDishes ~ authStr", authStr);

const response = await axios .get( url, { params: { categoryId: 1, }, }, { headers: { Authorization: authStr } } ) .catch((error) => { console.log("πŸŸ₯ ~ file: menu.js:108 ~ getDishes ~ error", error); }); console.log("πŸš€ ~ file: menu.js:112 ~ getDishes ~ response", response); } When I use the function as above I receive error [AxiosError: Request failed with status code 401] --> Which If I understand correctly means that my token expired or maybe wrong

When I set the headers before the params like this

export async function getDishes() { const url = DishesAuthURL;

const userToken = newUser.getToken();

const authStr = "Bearer ".concat(userToken); console.log("πŸš€ ~ file: menu.js:108 ~ getDishes ~ authStr", authStr);

const response = await axios .get( url,

  { headers: { Authorization: authStr } },
  {
    params: {
      categoryId: 1,
    },
  }
)
.catch((error) => {
  console.log("πŸŸ₯ ~ file: menu.js:108 ~ getDishes ~ error", error);
});

console.log("πŸš€ ~ file: menu.js:112 ~ getDishes ~ response", response); } I receive error [AxiosError: Request failed with status code 415] --> which is supposedly a bad request.

I am 100% sure that the token is working fine, tried it on postman and works fine.

I have tried to data,config instead of params and still the same issue.

I want to send the categoryId as a parameter in the request body like this while setting the Authorization with Bearer${userToken}

Screenshot 2023-01-09 at 8 38 24 PM

=====================

I re-wrote the entire function as follows

export async function getDishes() { var data = JSON.stringify({ categoryId: 4, });

// ========================

const url = DishesAuthURL; // console.log("πŸš€ ~ file: menu.js:84 ~ getDishes ~ url", url); let userToken = newUser.getToken(); const authStr = "Bearer ".concat(userToken);

// console.log("πŸš€ ~ file: menu.js:92 ~ getDishes ~ authStr", authStr); const options = { data: data, headers: { "": "", Authorization: authStr, "Content-Type": "application/json", }, method: "get", url: url, }; console.log("πŸš€ ~ file: menu.js:119 ~ getDishes ~ options", options); const response = await axios(options).catch((error) => { console.log("πŸŸ₯ ~ file: menu.js:103 ~ error from getting dishes", error); }); console.log(" βœ… ~ file: menu.js:105 ~ getDishes ~ response", response.data); }

and I now I get Error: header name must be a non-empty string