1

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?

alex
  • 524
  • 2
  • 11
  • "Error: bad port" — Presumably something is wrong with the port you put in the URL. – Quentin Jul 24 '22 at 21:41
  • "mode: 'no-cors'," — What is that doing there? Node.js doesn't encode the same origin policy in the first place. If it did, then doing that would prevent you setting the JSON content type. – Quentin Jul 24 '22 at 21:41
  • ""Access-Control-Allow-Origin": "*"," — What is that doing there? Node.js doesn't encode the same origin policy in the first place. If it did, then that would need to go on the response not the request. – Quentin Jul 24 '22 at 21:42
  • "ExperimentalWarning: The Fetch API is an experimental feature." — so maybe you found a bug – Quentin Jul 24 '22 at 21:43
  • @Quentin, Thanks for the comments , your first comment, why then the port is not wrong when using node fetch? Your second question about mode no-cors, that's my mistake and I'll fix it now, but it doesn't affect the result in any way. – alex Jul 24 '22 at 21:54

0 Answers0