我正在尝试获取curl并从API获取JSON。
curl -XPOST -d "grant_type=password" -d "username=admin@admin.admin" \
-d "password=admin" "web_app@localhost:8081/oauth/token"
当我在终端中使用curl时,一切正常,但尝试使用fetch时,我收到底部提到的错误消息。
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 is an url with embedded credentials.
我的抓取操作是否错误?
最佳答案
您不能使用https://user:pass@host.com
表单,您需要设置授权http header :
var headers = new Headers({
'Authorization': `Basic ${btoa(username + ':' + password)}`
});
fetch('https://host.com', {headers: headers})
其中 btoa
将“user:pass”编码为 Base64 编码字符串。您可以在 MDN 上找到 btoa
功能可用性(简而言之:它适用于 IE 10 及更高版本)。
关于javascript - 使用包含凭据的 URL 进行请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45067331/