jsDev
jsDev

Reputation: 186

Send Authentication header with fetch or axios

How to send authentication header with fetch or axios ?

I have tried to do it but it on my client side haven't any header with Authentification value.

Here is my code example.

let myHeaders = new Headers();
myHeaders.append("Authorization", token);
myHeaders.append("Access-Control-Allow-Origin", "*");
myHeaders.append("Access-Control-Allow-Origin", "*");

let req = {
        method: "GET",
        headers: myHeaders,
        mode: "no-cors",
        credentials: "same-origin",
    }
    fetch('http://localhost:5000/secret', req)
        .then(res => console.log(res))
        .catch(err => console.log(err))

And I tried check it on my node.js code.

router.route("/").get(passportJWT, SecretController.secret);

Upvotes: 0

Views: 2675

Answers (1)

Quentin
Quentin

Reputation: 943697

For two origins to be considered "the same", they must share:

  • Scheme (e.g. https)
  • Hostname
  • Port

You are making a request from http://localhost:3000 to http://localhost:5000 so are making a cross-origin request.

credentials: "same-origin"

… but you've restricted credentials (like Authorization) to same-origin requests.

mode: "no-cors",

To send credentials with a cross-origin request, you must have permission via CORS.

You must not set no-cors.

You need

mode: "cors",
credentials: "include"

Upvotes: 1

Related Questions