Axios 409 error

Describe the issue Hi, I'm doing a call to POST method of an API developed in .Net Core 3.0, as show in the Example Code, from a project in React.Js. Example Code const newCall = await axios.po...

Describe the issue

Hi, I’m doing a call to POST method of an API developed in .Net Core 3.0, as show in the Example Code, from a project in React.Js.

Example Code

const newCall = await axios.post(/colectoras,
{
cantidad: quantity,
idModelo: operativeModelId,
idRampa: rampId,
idSector: operativeSectorId,
idUnidad: unitWorkId,
sucursal: branchId,
usuario: userLogin
},
{
headers: {
‘Access-Control-Allow-Origin’: Config.get(‘apiOperacinesUrl’),
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/json; charset=UTF-8’
}
}).then(response => response)
.catch(error => error);

Expected behavior, if applicable

I hope receive an StatusCode with code 200 or error code, for example 409, but I receive the next message:

Error: Network Error
at createError (createError.js:17)
at XMLHttpRequest.handleError (xhr.js:80)

But if I call to the API from Postman, for example, I receive the next result:

{
«type»: «about:blank»,
«title»: «Error al crear colectoras»,
«status»: 409,
«detail»: » La unidad de trabajo BEN_OTROS ya tiene la colectora creada (en sucursal 1).»
}

Environment

  • Axios Version 0.19.0
  • Adapter HTTP
  • Browser Chrome
  • Browser Version 87.0.4280.88 (Build oficial) (64 bits)
  • Node.js Version v13.12.0
  • Windows 10 Pro 64 bits
  • Additional Library Versions React.JS Version 16.8.0

Additional context/Screenshots

The API called, use the a Carter Module, for manage the HTTP call.

Originally posted by IronCub3 July 18, 2022
Hi, I’ve got a nodejs + express serve and I wanted to make an axios request to an external API my code for this request is this:

const Axios = axios.default;

router.get("/infos", (req, res) => {
    console.log('Request HTTP Version: ', req.httpVersion);
          Axios.get("http://IP:PORT/path/to/endpoint",
        { headers: {
            "Content-Type": "application/json",
            "USER-NAME":"MY-USER",
            "USER-TOKEN":"MY-JWT"
        }}).then((resp: any) => {
            console.log(resp.data);
        }).catch((err: any) => {
            console.log(err);
        });
    });

But when i do the request to my path the erro that i get is:

[1] AxiosError: Parse Error: Expected HTTP/
[1] at Socket.socketOnData (node:_http_client:494:22)
[1] at Socket.emit (node:events:527:28)
[1] at addChunk (node:internal/streams/readable:315:12)
[1] at readableAddChunk (node:internal/streams/readable:289:9)
[1] at Socket.Readable.push (node:internal/streams/readable:228:10)
[1] at TCP.onStreamRead (node:internal/stream_base_commons:190:23)
[1] at TCP.callbackTrampoline (node:internal/async_hooks:130:17) {
[1] rawPacket: <Buffer 48 54 54 50 2f 31 2e 31 20 32 30 30 20 4f 4b 0d 0a 43 6f 6e 74 65 6e 74 2d 4c 65 6e 67 74 68 3a 20 34 31 38 0d 0a 43 6f 6e 74 65 6e 74 2d 54 79 70 65 … 459 more bytes>,
[1] reason: ‘Expected HTTP/’,
[1] code: ‘HPE_INVALID_CONSTANT’,
[1] bytesParsed: 490,
[1] config: {
[1] transitional: {
[1] silentJSONParsing: true,
[1] forcedJSONParsing: true,
[1] clarifyTimeoutError: false
[1] },
[1] adapter: [Function: httpAdapter],
[1] transformRequest: [ [Function: transformRequest] ],
[1] transformResponse: [ [Function: transformResponse] ],
[1] timeout: 0,
[1] xsrfCookieName: ‘XSRF-TOKEN’,
[1] xsrfHeaderName: ‘X-XSRF-TOKEN’,
[1] maxContentLength: -1,
[1] maxBodyLength: -1,
[1] env: { FormData: [Function] },
[1] validateStatus: [Function: validateStatus],
[1] headers: {
[1] Accept: ‘application/json, text/plain, /‘,
[1] ‘Content-Type’: ‘application/json’,
[1] ‘USER-NAME’: ‘MY-USER’,
[1] ‘USER-TOKEN’: ‘MY-JWT’,
[1] ‘User-Agent’: ‘axios/0.27.2’
[1] },
[1] method: ‘get’,
[1] url: ‘http://IP:PORT/path/to/endpoint,
[1] data: undefined
[1] },
[1] request: <ref *1> Writable {
[1] _writableState: WritableState {
[1] objectMode: false,
[1] highWaterMark: 16384,
[1] finalCalled: false,
[1] needDrain: false,
[1] ending: false,
[1] ended: false,
[1] finished: false,
[1] destroyed: false,
[1] decodeStrings: true,
[1] defaultEncoding: ‘utf8’,
[1] length: 0,
[1] writing: false,
[1] corked: 0,
[1] sync: true,
[1] bufferProcessing: false,
[1] onwrite: [Function: bound onwrite],
[1] writecb: null,
[1] writelen: 0,
[1] afterWriteTickInfo: null,
[1] buffered: [],
[1] bufferedIndex: 0,
[1] allBuffers: true,
[1] allNoop: true,
[1] pendingcb: 0,
[1] constructed: true,
[1] prefinished: false,
[1] errorEmitted: false,
[1] emitClose: true,
[1] autoDestroy: true,
[1] errored: null,
[1] closed: false,
[1] closeEmitted: false,
[1] [Symbol(kOnFinished)]: []
[1] },
[1] _events: [Object: null prototype] {
[1] response: [Function: handleResponse],
[1] error: [Function: handleRequestError],
[1] socket: [Function: handleRequestSocket]
[1] },
[1] _eventsCount: 3,
[1] _maxListeners: undefined,
[1] _options: {
[1] maxRedirects: 21,
[1] maxBodyLength: 10485760,
[1] protocol: ‘http:’,
[1] path: ‘/path/to/endpoint’,
[1] method: ‘GET’,
[1] headers: [Object],
[1] agent: undefined,
[1] agents: [Object],
[1] auth: undefined,
[1] hostname: ‘IP’,
[1] port: ‘PORT’,
[1] nativeProtocols: [Object],
[1] pathname: ‘/path/to/endpoint’
[1] },
[1] _ended: true,
[1] _ending: true,
[1] _redirectCount: 0,
[1] _redirects: [],
[1] _requestBodyLength: 0,
[1] _requestBodyBuffers: [],
[1] _onNativeResponse: [Function (anonymous)],
[1] _currentRequest: ClientRequest {
[1] _events: [Object: null prototype],
[1] _eventsCount: 7,
[1] _maxListeners: undefined,
[1] outputData: [],
[1] outputSize: 0,
[1] writable: true,
[1] destroyed: false,
[1] _last: true,
[1] chunkedEncoding: false,
[1] shouldKeepAlive: false,
[1] maxRequestsOnConnectionReached: false,
[1] _defaultKeepAlive: true,
[1] useChunkedEncodingByDefault: false,
[1] sendDate: false,
[1] _removedConnection: false,
[1] _removedContLen: false,
[1] _removedTE: false,
[1] _contentLength: 0,
[1] _hasBody: true,
[1] _trailer: »,
[1] finished: true,
[1] _headerSent: true,
[1] _closed: false,
[1] socket: [Socket],
[1] _header: ‘GET /path/to/endpoint HTTP/1.1rn’ +
[1] ‘Accept: application/json, text/plain, /rn’ +
[1] ‘Content-Type: application/jsonrn’ +
[1] ‘USER-NAME: MY-USERrn’ +
[1] ‘USER-TOKEN: MY-JWTrn’ +
[1] ‘User-Agent: axios/0.27.2rn’ +
[1] ‘Host: IP:PORTrn’ +
[1] ‘Connection: closern’ +
[1] ‘rn’,
[1] _keepAliveTimeout: 0,
[1] _onPendingData: [Function: nop],
[1] agent: [Agent],
[1] socketPath: undefined,
[1] method: ‘GET’,
[1] maxHeaderSize: undefined,
[1] insecureHTTPParser: undefined,
[1] path: ‘/path/to/endpoint’,
[1] _ended: true,
[1] res: [IncomingMessage],
[1] aborted: false,
[1] timeoutCb: null,
[1] upgradeOrConnect: false,
[1] parser: null,
[1] maxHeadersCount: null,
[1] reusedSocket: false,
[1] host: ‘IP’,
[1] protocol: ‘http:’,
[1] _redirectable: [Circular *1],
[1] [Symbol(kCapture)]: false,
[1] [Symbol(kNeedDrain)]: false,
[1] [Symbol(corked)]: 0,
[1] [Symbol(kOutHeaders)]: [Object: null prototype]
[1] },
[1] _currentUrl: ‘http://IP:PORT/path/to/endpoint’,
[1] [Symbol(kCapture)]: false
[1] }
[1] }

Other specs:
NodeJS version: 16.15.1

«axios»: «^0.27.2»,
«cors»: «^2.8.5»,
«express»: «^4.18.1»

The path dose not contain any spaces and is an end point of another software API, if i curl the API with the same headers from remote i get a successful response but using axios I get the error mentioned above.
Can some one help at solve this problem? I’ve looked up to some other similar problems but they are all different from this.

Thanks in advance.

This may seem stupid, but I’m trying to get the error data when a request fails in Axios.

axios
  .get('foo.example')
  .then((response) => {})
  .catch((error) => {
    console.log(error); //Logs a string: Error: Request failed with status code 404
  });

Instead of the string, is it possible to get an object with perhaps the status code and content? For example:

Object = {status: 404, reason: 'Not found', body: '404 Not found'}

Stephen Ostermiller's user avatar

asked Aug 25, 2016 at 19:13

Sebastian Olsen's user avatar

Sebastian OlsenSebastian Olsen

10.1k9 gold badges42 silver badges89 bronze badges

What you see is the string returned by the toString method of the error object. (error is not a string.)

If a response has been received from the server, the error object will contain the response property:

axios.get('/foo')
  .catch(function (error) {
    if (error.response) {
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    }
  });

answered Aug 25, 2016 at 19:34

Nick Uraltsev's user avatar

Nick UraltsevNick Uraltsev

23.7k4 gold badges24 silver badges14 bronze badges

17

With TypeScript, it is easy to find what you want with the right type.

This makes everything easier because you can get all the properties of the type with autocomplete, so you can know the proper structure of your response and error.

import { AxiosResponse, AxiosError } from 'axios'

axios.get('foo.example')
  .then((response: AxiosResponse) => {
    // Handle response
  })
  .catch((reason: AxiosError) => {
    if (reason.response!.status === 400) {
      // Handle 400
    } else {
      // Handle else
    }
    console.log(reason.message)
  })

Also, you can pass a parameter to both types to tell what are you expecting inside response.data like so:

import { AxiosResponse, AxiosError } from 'axios'
axios.get('foo.example')
  .then((response: AxiosResponse<{user:{name:string}}>) => {
    // Handle response
  })
  .catch((reason: AxiosError<{additionalInfo:string}>) => {
    if (reason.response!.status === 400) {
      // Handle 400
    } else {
      // Handle else
    }
    console.log(reason.message)
  })

Stephen Ostermiller's user avatar

answered Sep 17, 2019 at 3:03

Yan QiDong's user avatar

3

As @Nick said, the results you see when you console.log a JavaScript Error object depend on the exact implementation of console.log, which varies and (imo) makes checking errors incredibly annoying.

If you’d like to see the full Error object and all the information it carries bypassing the toString() method, you could just use JSON.stringify:

axios.get('/foo')
  .catch(function (error) {
    console.log(JSON.stringify(error))
  });

answered Feb 14, 2017 at 9:17

danii's user avatar

daniidanii

5,5132 gold badges21 silver badges23 bronze badges

2

There is a new option called validateStatus in request config. You can use it to specify to not throw exceptions if status < 100 or status > 300 (default behavior). Example:

const {status} = axios.get('foo.example', {validateStatus: () => true})

Stephen Ostermiller's user avatar

answered Mar 31, 2020 at 12:44

Dmytro Naumenko's user avatar

You can use the spread operator (...) to force it into a new object like this:

axios.get('foo.example')
    .then((response) => {})
    .catch((error) => {
        console.log({...error})
})

Be aware: this will not be an instance of Error.

Stephen Ostermiller's user avatar

answered Jan 22, 2020 at 20:31

Moses Schwartz's user avatar

Moses SchwartzMoses Schwartz

2,7181 gold badge19 silver badges31 bronze badges

0

I am using this interceptors to get the error response.

const HttpClient = axios.create({
  baseURL: env.baseUrl,
});

HttpClient.interceptors.response.use((response) => {
  return response;
}, (error) => {
  return Promise.resolve({ error });
});

answered Dec 5, 2016 at 16:41

Tan's user avatar

TanTan

3323 silver badges11 bronze badges

2

In order to get the http status code returned from the server, you can add validateStatus: status => true to axios options:

axios({
    method: 'POST',
    url: 'http://localhost:3001/users/login',
    data: { username, password },
    validateStatus: () => true
}).then(res => {
    console.log(res.status);
});

This way, every http response resolves the promise returned from axios.

https://github.com/axios/axios#handling-errors

answered May 7, 2020 at 11:48

Emre Tapcı's user avatar

Emre TapcıEmre Tapcı

1,68314 silver badges15 bronze badges

Whole error can only be shown using error.response like that :

axios.get('url').catch((error) => {
      if (error.response) {
        console.log(error.response);
      }
    });

answered Jul 1, 2021 at 10:07

Manik Verma's user avatar

const handleSubmit = (e) => {
e.preventDefault();
// console.log(name);
setLoading(true);
createCategory({ name }, user.token)
  .then((res) => {
   // console.log("res",res);
    setLoading(false);
    setName("");
    toast.success(`"${res.data.name}" is created`);
    loadCategories();
  })
  .catch((err) => {
    console.log(err);
    setLoading(false);
    if (err.response.status === 400) toast.error(err.response.data);//explained in GD
  });

};

See the console log then you will understand clearly

enter image description here

answered Oct 7, 2022 at 4:08

Shakil- The Coding monster's user avatar

With Axios

    post('/stores', body).then((res) => {

        notifyInfo("Store Created Successfully")
        GetStore()
    }).catch(function (error) {

        if (error.status === 409) {
            notifyError("Duplicate Location ID, Please Add another one")
        } else {
            notifyError(error.data.detail)
        }

    })

answered Sep 3, 2021 at 5:43

Rumesh Madushanka's user avatar

It’s indeed pretty weird that fetching only error does not return an object. While returning error.response gives you access to most feedback stuff you need.

I ended up using this:

axios.get(...).catch( error => { return Promise.reject(error.response.data.error); });

Which gives strictly the stuff I need: status code (404) and the text-message of the error.

answered Apr 27, 2021 at 12:14

Bogdan Antone's user avatar

You can put the error into an object and log the object, like this:

axios.get('foo.example')
    .then((response) => {})
    .catch((error) => {
        console.log({error}) // this will log an empty object with an error property
    });

Stephen Ostermiller's user avatar

answered Jan 22, 2020 at 21:29

Mendy's user avatar

MendyMendy

7,2205 gold badges28 silver badges40 bronze badges

Axios. get('foo.example')
.then((response) => {})
.catch((error) => {
    if(error. response){
       console.log(error. response. data)
       console.log(error. response. status);

      }
})

Stephen Ostermiller's user avatar

answered Jan 14, 2021 at 5:59

Vignesh's user avatar

VigneshVignesh

1371 silver badge5 bronze badges

3

It’s my code: Work for me

 var jsonData = request.body;
    var jsonParsed = JSON.parse(JSON.stringify(jsonData));

    // message_body = {
    //   "phone": "5511995001920",
    //   "body": "WhatsApp API on chat-api.com works good"
    // }

    axios.post(whatsapp_url, jsonParsed,validateStatus = true)
    .then((res) => {
      // console.log(`statusCode: ${res.statusCode}`)

            console.log(res.data)
        console.log(res.status);

        // var jsonData = res.body;
        // var jsonParsed = JSON.parse(JSON.stringify(jsonData));

        response.json("ok")
    })
    .catch((error) => {
      console.error(error)
        response.json("error")
    })

answered Jul 4, 2020 at 12:17

Rodrigo Grossi's user avatar

Понравилась статья? Поделить с друзьями:
  • Awk line 1 syntax error at or near
  • Awesome cannot open display error 5
  • Awe 2221 whirlpool коды ошибок
  • Awe 2215 whirlpool ошибки
  • Awd ошибка на инфинити qx60