简体   繁体   中英

Fetch endpoint with basic auth gives 401

I'm trying to call an endpoint with basic auth. I made a REACT application that needs to make api calls.

This is my code:

 const base64 = require('base-64'); const login = base64.encode("username:password"); const fetchTemplates = async () => { console.log(login); // shows: dXNlcm5hbWU6cGFzc3dvcmQ= const response = await fetch("http://localhost:8080/students/chat/templates", { mode: "no-cors", headers: new Headers({"Authorization": `Basic ${login}`}) }); const data = await response.json(); if (response.status > 400) { console.log(data.errors); throw new Error(data.errors); } console.log(data); return data; } export { fetchTemplates } 

I'm not sure what i'm doing wrong here. Accessing the endpoint from browser works fine with the same credentials i use in my code. Normally i should be able to see the Authorization in the request header in the console. But there is nothing.

Any help is welcome.

Thanks in advance.

Long story short: no-cors mode restricts the kinds of headers that you can send. Authorization is not one of those headers. So you have to remove no-cors mode in order to use the Authorization header.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM