使用包含凭证的URL进行请求 [英] Request with URL that includes credentials
问题描述
我正在尝试获取curl并从API中获取JSON.
I'm trying to fetch a curl and get a JSON from an API.
curl -XPOST -d "grant_type=password" -d "username=admin@admin.admin" \
-d "password=admin" "web_app@localhost:8081/oauth/token"
当我在终端中使用curl时,一切正常,但是尝试进行读取时,我得到了底部提到的错误消息.
When I use the curl in terminal everything works fine but trying it with a fetch I get the error message mentioned at the bottom.
fetch("http://web_app@localhost:8081/oauth/token", {
credentials: 'include',
body: "grant_type=password&username=admin@admin.admin&password=admin",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
method: "POST"
}
这是我得到的错误:
TypeError: http://web_app @ localhost:8081/oauth/token 是一个网址和 嵌入式凭据.
TypeError: http://web_app@localhost:8081/oauth/token is an url with embedded credentials.
我做错了吗?
推荐答案
您不能使用https://user:pass@host.com
表单,需要设置Authorization http Header:
You can't use the https://user:pass@host.com
form, you need to set the Authorization http Header:
var headers = new Headers();
headers.append('Authorization', 'Basic ' + btoa(username + ':' + password));
fetch('https://host.com', {headers: headers})
其中btoa
将'user:pass'编码为base64编码的字符串.您可以在 MDN btoa函数可用性>(简而言之:它适用于IE 10及更高版本).
Where btoa
encodes 'user:pass' to base64 encoded string. You can find btoa
function availability on MDN (in short: it works on IE 10 and above).
这篇关于使用包含凭证的URL进行请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!