Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios post request with header not working

I have used axios for calling network request in react-Native but it return 500 response code.

Note: It's working perfect in postman client.

Authorization Token:

Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImlzcyI6Imh0dHA6Ly9hcHBzZGF0YTIuY2xvdWRhcHAubmV0L2p3dC1kZW1vL3B1YmxpYy9hcGkvbG9naW4iLCJpYXQiOjE1MDYzMzkwNDgsImV4cCI6MTY2MTg1OTA0OCwibmJmIjoxNTA2MzM5MDQ4LCJqdGkiOiJHUWt5RVlwck5GSDBHekd4In0.JqdyAEkEN_D3M2WbqcQwIwghk6iajFjxi9g854akjB8

code

const token = 'Bearer '.concat(this.state.token);

var headers = {
  'Content-Type': 'application/json',
  'Authorization': token
}

axios.post('http://appsdata2.cloudapp.net/jwt-demo/public/api/profile',
  null,
  headers)
.then((response ) => {
  console.log("reactNativeDemo","response get details:"+response.data);
})
.catch((error) => {
  console.log("axios error:",error);
});

Log from try catch

'axios error:', { [Error: Request failed with status code 500]
 config: 
 { adapter: [Function: xhrAdapter],
  transformRequest: { '0': [Function: transformRequest] },
  transformResponse: { '0': [Function: transformResponse] },
  timeout: 0,
  xsrfCookieName: 'XSRF-TOKEN',
  xsrfHeaderName: 'X-XSRF-TOKEN',
  maxContentLength: -1,
  validateStatus: [Function: validateStatus],
  headers: 
  { Accept: 'application/json, text/plain, */*',
  'Content-Type': 'application/x-www-form-urlencoded' },
  method: 'post',
  'Content-Type': 'application/json',
  Authorization: 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImlzcyI6Imh0dHA6Ly9hcHBzZGF0YTIuY2xvdWRhcHAubmV0L2p3dC1kZW1vL3B1YmxpYy9hcGkvbG9naW4iLCJpYXQiOjE1MDYzMzkwNDgsImV4cCI6MTY2MTg1OTA0OCwibmJmIjoxNTA2MzM5MDQ4LCJqdGkiOiJHUWt5RVlwck5GSDBHekd4In0.JqdyAEkEN_D3M2WbqcQwIwghk6iajFjxi9g854akjB8',
  url: 'http://appsdata2.cloudapp.net/jwt-demo/public/api/profile',
  data: null },
  request: 
  { UNSENT: 0,
    OPENED: 1,
    HEADERS_RECEIVED: 2,
    LOADING: 3,
    DONE: 4,
    readyState: 4,
    status: 500,
    timeout: 0,
    withCredentials: true,
    upload: {},
    _aborted: false,
    _hasError: false,
    _method: 'POST',
    _response: '{"meta":{"message":"Unable to get token in your request."}}',
    _url: 'http://appsdata2.cloudapp.net/jwt-demo/public/api/profile',
    _timedOut: false,
    _trackingName: 'unknown',
    _incrementalEvents: false,
    responseHeaders: 
    { expires: '-1',
    pragma: 'no-cache',
    Server: 'nginx',
    Date: 'Mon, 25 Sep 2017 11:30:49 GMT',
    'Keep-Alive': 'timeout=60',
    'Content-Type': 'application/json',
    'Content-Length': '59',
    Connection: 'keep-alive',
    'X-RateLimit-Remaining': '58',
    'X-Powered-By': 'PHP/5.6.23-1+deprecated+dontuse+deb.sury.org~trusty+1',
    'Cache-Control': 'private, must-revalidate',
    'X-RateLimit-Limit': '60' },
    _requestId: null,
    _cachedResponse: undefined,
    _headers: 
    { accept: 'application/json, text/plain, */*',
    'content-type': 'application/x-www-form-urlencoded' },
    _responseType: '',
    _sent: true,
    _lowerCaseResponseHeaders: 
    { expires: '-1',
    pragma: 'no-cache',
    server: 'nginx',
    date: 'Mon, 25 Sep 2017 11:30:49 GMT',
    'keep-alive': 'timeout=60',
    'content-type': 'application/json',
    'content-length': '59',
    connection: 'keep-alive',
    'x-ratelimit-remaining': '58',
    'x-powered-by': 'PHP/5.6.23-1+deprecated+dontuse+deb.sury.org~trusty+1',
    'cache-control': 'private, must-revalidate',
    'x-ratelimit-limit': '60' },
    _subscriptions: [],
    responseURL: 'http://appsdata2.cloudapp.net/jwt-demo/public/api/profile' },
    response: 
    { data: { meta: { message: 'Unable to get token in your request.' } },
    status: 500,
    statusText: undefined,
    headers: 
    { expires: '-1',
    pragma: 'no-cache',
    server: 'nginx',
    date: 'Mon, 25 Sep 2017 11:30:49 GMT',
    'keep-alive': 'timeout=60',
    'content-type': 'application/json',
    'content-length': '59',
    connection: 'keep-alive',
    'x-ratelimit-remaining': '58',
    'x-powered-by': 'PHP/5.6.23-1+deprecated+dontuse+deb.sury.org~trusty+1',
    'cache-control': 'private, must-revalidate',
    'x-ratelimit-limit': '60' },
    config: 
    { adapter: [Function: xhrAdapter],
     transformRequest: { '0': [Function: transformRequest] },
     transformResponse: { '0': [Function: transformResponse] },
     timeout: 0,
     xsrfCookieName: 'XSRF-TOKEN',
     xsrfHeaderName: 'X-XSRF-TOKEN',
     maxContentLength: -1,
     validateStatus: [Function: validateStatus],
     headers: 
     { Accept: 'application/json, text/plain, */*',
     'Content-Type': 'application/x-www-form-urlencoded' },
     method: 'post',
     'Content-Type': 'application/json',
like image 291
Kishore Jethava Avatar asked Sep 25 '17 11:09

Kishore Jethava


2 Answers

Axios post methods syntax is as follows: axios.post(url[, data[, config]])

So you should do something like this:

axios.post('http://appsdata2.cloudapp.net/jwt-demo/public/api/profile',
null,
{headers: headers})
.then((response ) => {
  console.log("reactNativeDemo","response get details:"+response.data);
})
.catch((error) => {
  console.log("axios error:",error);
});

I tried this in https://npm.runkit.com/axios and works well Please check here

like image 65
Apurva jain Avatar answered Sep 21 '22 09:09

Apurva jain


I had problems with that too. If you want try this if this resolves your issue.

NOTE: This is configuring your global options. If this works for you try to create instances

const setAxiosToken = (token) => {
  axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
  axios.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8'
}
setAxiosToken(YOUR_TOKEN)
axios.post('http://appsdata2.cloudapp.net/jwt-demo/public/api/profile')
like image 28
Panagiotis Vrs Avatar answered Sep 21 '22 09:09

Panagiotis Vrs