Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

api - Request with URL that includes credentials

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"

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"
    }

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...