'HTTPS Request returns getaddrinfo ENOTFOUND
I am attempting to make an HTTPS POST request to the https://petstore.swagger.io/v2/pets endpoint. Documentation can be found here: https://petstore.swagger.io/#/. It works fine using Postman, but when I make the same request, with the same data using Node.js I get the following error:
Error: getaddrinfo ENOTFOUND petstore.swagger.io/v2
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:67:26) {
errno: -3008,
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'petstore.swagger.io/v2'
}
Here is the complete code:
import * as https from 'https';
async function main() {
const data = JSON.stringify({
name: 'doggie',
photoUrls: [
"string"
]
});
const options = {
hostname: "petstore.swagger.io/v2",
path: "/pet",
body: data
}
try {
let response = await httpRequest(options);
console.log(response);
} catch (err) {
console.log(err);
}
}
function httpRequest(options) {
return new Promise((resolve, reject) => {
const clientRequest = https.request(options, incomingMessage => {
// Response object.
let response = {
statusCode: incomingMessage.statusCode,
headers: incomingMessage.headers,
body: []
};
// Collect response body data.
incomingMessage.on('data', chunk => {
response.body.push(chunk);
});
// Resolve on end.
incomingMessage.on('end', () => {
if (response.body.length) {
response.body = response.body.join();
try {
response.body = JSON.parse(response.body);
} catch (error) {
// Silently fail if response is not JSON.
}
}
resolve(response);
});
});
// Reject on request error.
clientRequest.on('error', error => {
reject(error);
});
// Write request body if present.
if (options.body) {
clientRequest.write(options.body);
}
// Close HTTP connection.
clientRequest.end();
});
}
main();
What am I messing up? Thanks!
Solution 1:[1]
Host name contains only the domain, not the rest of the path. You also need to provide the HTTP method and the content type.
const options = {
hostname: "petstore.swagger.io",
path: "/v2/pet",
body: data,
method: "POST",
headers: {
'Content-Type': 'application/json'
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | harsh989 |