0

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);

9
  • 1
    "Does not work" is not a useful problem statement. Describe the error, or response(s), or issue clearly. Note that a problem well defined is half solved already. Apr 27, 2018 at 13:30
  • are you fetching from the same origin? experiment with credentials: "include", Apr 27, 2018 at 13:33
  • Access-Control-Allow-Origin is a response header; it does not belong on a request!!
    – Quentin
    Apr 27, 2018 at 13:35
  • mode: "no-cors" — Why are you doing that?
    – Quentin
    Apr 27, 2018 at 13:35
  • @TiagoCoelho yes, I am.
    – jsDev
    Apr 27, 2018 at 13:36

1 Answer 1

1

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"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.