最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Request with URL that includes credentials - Stack Overflow

programmeradmin1浏览0评论

I'm trying to fetch a curl and get a JSON from an API.

curl -XPOST -d "grant_type=password" -d "[email protected]" \
    -d "password=admin" "web_app@localhost:8081/oauth/token"

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&[email protected]&password=admin",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
        },
        method: "POST"
    }

This is the error I get:

TypeError: http://web_app@localhost:8081/oauth/token is an url with embedded credentials.

Is the fetch I did wrong?

I'm trying to fetch a curl and get a JSON from an API.

curl -XPOST -d "grant_type=password" -d "[email protected]" \
    -d "password=admin" "web_app@localhost:8081/oauth/token"

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&[email protected]&password=admin",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
        },
        method: "POST"
    }

This is the error I get:

TypeError: http://web_app@localhost:8081/oauth/token is an url with embedded credentials.

Is the fetch I did wrong?

Share Improve this question edited Aug 9, 2023 at 21:12 Brian Tompsett - 汤莱恩 5,88372 gold badges61 silver badges133 bronze badges asked Jul 12, 2017 at 20:53 CptRivailleCptRivaille 2491 gold badge2 silver badges5 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 42 +350

You can't use the https://user:[email protected] form, you need to set the Authorization http Header:

var headers = new Headers({
    'Authorization': `Basic ${btoa(username + ':' + password)}`
});

fetch('https://host.com', {headers: headers})

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).

发布评论

评论列表(0)

  1. 暂无评论