使用包含凭据的 URL 请求 [英] Request with URL that includes credentials
问题描述
我正在尝试从 API 获取 curl 并获取 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 时,一切正常,但尝试使用 fetch 时,我收到底部提到的错误消息.
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 是一个 url和嵌入式凭据.
TypeError: http://web_app@localhost:8081/oauth/token is an url with embedded credentials.
我的抓取有误吗?
推荐答案
不能使用https://user:pass@host.com
形式,需要设置Authorization http标题:
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 编码的字符串.您可以在 btoa 功能可用性>MDN(简而言之:它适用于 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屋!