The problem is that you are assuming the error is returned in the response. It could also be in the request (e.g. while connecting to the server before making the request). I addded console.log(error)
and found that on my computer the error is in the request:
AxiosError: connect ECONNREFUSED 38.238.92.52:443
at AxiosError.from (/run/user/1000/test123/node_modules/axios/dist/node/axios.cjs:725:14)
at RedirectableRequest.handleRequestError (/run/user/1000/test123/node_modules/axios/dist/node/axios.cjs:2467:25)
at RedirectableRequest.emit (node:events:513:28)
at eventHandlers.<computed> (/run/user/1000/test123/node_modules/follow-redirects/index.js:14:24)
at ClientRequest.emit (node:events:513:28)
at TLSSocket.socketErrorListener (node:_http_client:494:9)
at TLSSocket.emit (node:events:513:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
port: 443,
address: '38.238.92.52',
syscall: 'connect',
code: 'ECONNREFUSED',
errno: -111,
config: {
[...]
},
request: <ref *1> Writable {
[...]
},
cause: Error: connect ECONNREFUSED 38.238.92.52:443
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1300:16) {
errno: -111,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '38.238.92.52',
port: 443
}
}
/run/user/1000/test123/test.js:11
console.log(error.response.data);
^
TypeError: Cannot read properties of undefined (reading 'data')
at /run/user/1000/test123/test.js:11:32
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
Node.js v18.10.0
The server you are connecting to does not seem to support HTTPS. It can only be connected to if https://www.icofont.cn//sd
is changed to http://www.icofont.cn//sd
, and then the 404 comes out.
Instead of assuming the error is in the response or request, it should be checked for. The official example explains this.
Your fixed example will look like the following:
const axios = require('axios');
axios({
url:'http://www.icofont.cn//sd',
method:'GET',
})
.then(response=>{
console.log(response.status);
})
.catch(error=>{
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
})