请求包含凭据的URL

时间:2017-07-12 20:53:24

标签: api reactjs curl fetch-api

我正在尝试获取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是一个网址   嵌入式凭证。

抓取我做错了吗?

1 个答案:

答案 0 :(得分:8)

您无法使用https://user:pass@host.com表单,您需要设置授权http标头:

var headers = new Headers();

headers.append('Authorization', 'Basic ' + btoa(username + ':' + password));
fetch('https://host.com', {headers: headers})

btoa编码'用户:传递'到base64编码的字符串。您可以在MDN上找到btoa功能可用性(简而言之:它适用于IE 10及更高版本)。

相关问题