简体   繁体   English

使用基本身份验证获取端点会给出401

[英]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. 我做了一个REACT应用程序,需要进行api调用。

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. 长话短说:no-cors模式限制了您可以发送的标头的种类。 Authorization is not one of those headers. 授权不是这些标头之一。 So you have to remove no-cors mode in order to use the Authorization header. 因此,您必须删除no-cors模式才能使用Authorization标头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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