So, I have a server on amazon with my application, I need to do authorization with nodejs project. Using fetch, I tried to authorize but I get an error below my code.
async function Login() {
try {
const response = await fetch("https://xx.xxx.xx.xx:XXXXX/auth/login", {
method: 'POST',
headers: {
"Content-Type": "application/json; charset=utf-8"
},
body: JSON.stringify({
email: "",
password: "",
})
});
if (!response.ok) {
throw new Error(`Error! status: ${response.status}`);
}
console.log(await response.json())
const result = await response.json();
return result;
} catch (err) {
console.log(err);
}
}
Fetch ERROR:
TypeError: fetch failed
at Object.processResponse (node:internal/deps/undici/undici:5536:34)
at node:internal/deps/undici/undici:5858:42
at node:internal/process/task_queues:140:7
at AsyncResource.runInAsyncScope (node:async_hooks:202:9)
at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8) {
cause: Error: bad port
at makeNetworkError (node:internal/deps/undici/undici:4664:51)
at mainFetch (node:internal/deps/undici/undici:5677:20)
at fetching (node:internal/deps/undici/undici:5664:7)
at Agent.fetch2 (node:internal/deps/undici/undici:5547:20)
at Object.fetch (node:internal/deps/undici/undici:6332:20)
at fetch (node:internal/bootstrap/pre_execution:196:25)
at getUser (file:///C:/project/auth/main.js:127:32)
at file:///C:/project/auth/main.js:154:1
at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
at async Promise.all (index 0) {
[cause]: undefined
}
}
(node:12956) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
But using node-fetch I don't get any error.
node-fetch code
import fetch from "node-fetch"
async function Login() {
try {
const response = await fetch("https://xx.xxx.xx.xx:XXXXX/auth/login", {
method: 'POST',
headers: {
"Content-Type": "application/json; charset=utf-8"
},
body: JSON.stringify({
email: "",
password: "",
})
});
if (!response.ok) {
throw new Error(`Error! status: ${response.status}`);
}
console.log(await response.json())
const result = await response.json();
return result;
} catch (err) {
console.log(err);
}
}
It's working.
Then I checked axios, I get an error, why?
async function Login() {
return await axios.post("https://xx.xxx.xx.xx:XXXXX/auth/login", {
headers: {
"Content-Type": "application/json; charset=utf-8"
},
withCredentials: true,
body: JSON.stringify({
email: "",
password: ""
})
})
}
Axios ERROR:
node:internal/process/esm_loader:91
internalBinding('errors').triggerUncaughtException(
^
AxiosError: connect EACCES xx.xxx.xx.xx:XXXXX
What am I doing wrong? Why does node-fetch work and everything else does not?