I want to send request from one localhost to another localhost running on this same machine.
First is localhost:3000
and second localhost:3005
.
Belowed code is from maching :3005
which is trying to send request to :3000
:
return new Promise<EventResponse>((resolve, reject) => {
const httpOptions= {
hostname: "http://localhost:3000", //not working also without http/https
method: 'POST',
path: '/api/something',
headers: {
"Content-Type": "application/json",
}
}
const request = http.request(httpOptions, (res: TraceoIncomingMessage) => {
res.setEncoding("utf8");
res.on("error", reject);
});
request.on("error", (err) => {
console.log("ERROR: ", err); //ENOTFOUND
reject;
});
request.on("timeout", () => {
request.destroy();
reject({
statusCode: 400
});
});
request.write(JSON.stringify(payload));
request.end();
});
Can someone tell me why above code throw me this:
ERROR: Error: getaddrinfo ENOTFOUND 127.0.0.1:3000
at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:71:26) {
errno: -3008,
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: '127.0.0.1:3000'
}
I'm sure that :3000
server is running during sending this request.
Thanks for any help!
CodePudding user response:
The error message is pretty clear: it says that it cannot find a host named 127.0.0.1:3000
, and that is perfectly understandable, since the colon character :
is illegal in hostnames, IPv4 addresses, and IPv6 addresses.
3000
is the port number, not part of the hostname. You have to pass 3000
as the port and 127.0.0.1
or localhost
as the hostname:
const httpOptions= {
hostname: "localhost",
port: 3000,
method: 'POST',
path: '/api/something',
headers: {
"Content-Type": "application/json",
}
}
Note that the same applies to http://
as well: forward slashes /
are also illegal in hostnames, IPv4 addresses, and IPv6 addresses. HTTP is the protocol, it is not part of the hostname. HTTP is the default protocol for http.request
, so there is no need to pass it. If you want a different protocol (e.g. HTTPS), you have to pass it:
const httpOptions= {
hostname: "localhost",
port: 3000,
protocol: 'https:',
method: 'POST',
path: '/api/something',
headers: {
"Content-Type": "application/json",
}
}
If I had to take a guess, I would say that the root cause of the problem is that you are confusing a URI, a hostname, a protocol, and a port. But that is just a guess.
CodePudding user response:
I would try this:
const httpOptions= {
hostname: "localhost",
port: 3000,
method: 'POST',
path: '/api/something',
headers: {
"Content-Type": "application/json",
}
}
CodePudding user response:
You shouldn't declare the port
or protocol
in the hostname
like that.
Modify your httpOptions
like so:
const httpOptions= {
hostname: "localhost",
port: 3000,
method: 'POST',
path: '/api/something',
headers: {
"Content-Type": "application/json",
}
}
You can read more on the httpOptions
here: Node HTTP.request([options])