jacob
jacob

Reputation: 1186

Spring server.address=localhost cannot connect from Node.js fetch api

I have solved this, but I still don't know why.

I have a Spring Boot server when I set "server.address=localhost", the server cannot connect any more from Node.js fetch API. But using web browser is okay, and when commenting "::1 localhost" line in the host file is okay too.

What is the reason for this problem?

When I request with "localhost:8082/xxxx", the error occurred:

fetch("http://localhost:8082/api/auth/test")
    .then(response => response.text())
    .then(data => console.log(data))
    .catch(err => console.error(err));
TypeError: fetch failed
    at Object.processResponse (node:internal/deps/undici/undici:6277:34)
    at node:internal/deps/undici/undici:6602:42
    at node:internal/process/task_queues:140:7
    at AsyncResource.runInAsyncScope (node:async_hooks:203:9)
    at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  cause: Error: connect ECONNREFUSED ::1:8082
      at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1247:16) {
    errno: -61,
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '::1',
    port: 8082
  }
}

If I use curl http://localhost:8082/api/auth/test, everything is okay, like this:

*   Trying 127.0.0.1:8082...
* Connected to localhost (127.0.0.1) port 8082 (#0)
> GET /api/auth/test HTTP/1.1
> Host: localhost:8082
> User-Agent: curl/7.88.1
> Accept: */*
> 
< HTTP/1.1 200 
< Vary: Origin
< Vary: Access-Control-Request-Method
< Vary: Access-Control-Request-Headers
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 0
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< Content-Type: text/plain;charset=UTF-8
< Content-Length: 11
< Date: Wed, 09 Aug 2023 09:52:05 GMT
< 
* Connection #0 to host localhost left intact
test ok 123%    

I have another try and found something new, If I config application.properties in spring, the request with "localhost" will be failed and get above error. If I don't config this, it will be okay.

I use fetch like this, and this fetch is in a pure nodejs project:

fetch("http://localhost:8080/test")
    .then(response => response.text())
    .then(data => console.log(data))
    .catch(error => console.error(error))

Upvotes: 1

Views: 272

Answers (1)

user20342916
user20342916

Reputation:

::1 localhost is a way to shorten localhost IPv6 addresses. A full string IPv6, like so xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx and this ::1 localhost works the same way because they are the same.

I wouldn't advice disabling IPv6 addressing since many public web servers are using them by default now.

EDIT: You might want to disable IPv6 to test it.

Upvotes: 0

Related Questions