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

javascript - Convert curl to ajax request - Stack Overflow

programmeradmin2浏览0评论

Simple question: is there any way to convert this curl to an ajax request?

curl -v  \
  -H "Accept: application/json" \
  -H "Accept-Language: en_US" \
  -u "1d75wsZ6y0SFdVsY9183IvxFyZp:EClusMEUk8e9ihI7ZdVLF" \
  -d "grant_type=client_credentials"

While I'm quite sure about what to do with -H, I've no idea of how to specify -u and -d.

Simple question: is there any way to convert this curl to an ajax request?

curl -v https://api.mydomain./v1/oauth2/token \
  -H "Accept: application/json" \
  -H "Accept-Language: en_US" \
  -u "1d75wsZ6y0SFdVsY9183IvxFyZp:EClusMEUk8e9ihI7ZdVLF" \
  -d "grant_type=client_credentials"

While I'm quite sure about what to do with -H, I've no idea of how to specify -u and -d.

Share Improve this question asked Jul 17, 2015 at 9:04 user1094081user1094081
Add a ment  | 

2 Answers 2

Reset to default 5

If you use XMLHTTPRequest you can use setRequestHeader for setting request headers (-H)

-u can be done by simple prepending the credentials to the url: https://1d75wsZ6y0SFdVsY9183IvxFyZp:[email protected]/v1/oauth2/token

-d is the POST body which should be the first argument in .send(body)

This should be a valid example using the jQuery Ajax method:

$.ajax({
    type: "POST",
    url: "https://api.mydomain./v1/oauth2/token",
    dataType: 'json',
    data: {"grant_type": "client_credentials"},
    beforeSend: function (xhr) {
        xhr.setRequestHeader('Authorization', 'Basic ' + [anylib].base64encode('1d75wsZ6y0SFdVsY9183IvxFyZp:EClusMEUk8e9ihI7ZdVLF'));
        xhr.setRequestHeader('Accept-Language', 'en_US');
    }
});

Edit - Native: (be aware of different browser implementation)

xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
  if(xhr.readyState==4 && xhr.status==200){
        consolelog(xhr.responseText);
  }
}
xhr.setRequestHeader('Authorization', 'Basic ' + [anylib].base64encode('1d75wsZ6y0SFdVsY9183IvxFyZp:EClusMEUk8e9ihI7ZdVLF'));
xhr.setRequestHeader('Accept-Language', 'en_US');
xhr.setRequestHeader("Content-type","application/json");
xhr.open("POST","https://api.mydomain./v1/oauth2/token",true);
xhr.send("grant_type=client_credentials");

Edit2: Just got told by a colleague you need to base64 encrypt your auth here.

发布评论

评论列表(0)

  1. 暂无评论