Google의 Shortener API를 통해 URL을 단축하기 위해 xmlhttpRequest를 사용하여

StackOverflow https://stackoverflow.com//questions/12699859

문제

jQuery / ajax를 통해이 작업을 시도했지만 작동하지 않으므로 정상적인 xmlhttprequest로 다시 떨어질 것이라고 생각했습니다.불행히도, 여전히 작동하지 않습니다 (동일한 문제).

다음은 "Nofollow"> Google의 게시물 요청 에 대한 문서가 있습니다.다음은 내 코드가 있습니다 :

var xmlHttp = new XMLHttpRequest();

xmlHttp.open("POST", "https://www.googleapis.com/urlshortener/v1/url", true);
xmlHttp.setRequestHeader("Content-Type", "application/json");

var url = "longUrl=" + encodeURIComponent("http://www.google.com/");
console.log(url);

xmlHttp.send(url);
.

"URL"은 다음과 같이 콘솔로 전송됩니다. longurl= http % 3A % 2F % 2fwww.google.com % 2F

응답은 다음과 같습니다.

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "parseError",
    "message": "Parse Error"
   }
  ],
  "code": 400,
  "message": "Parse Error"
 }
}
.

누구도 내가 뭘 잘못하고 있는지 보는가?

미리 감사드립니다!

편집 : @greg를 위해 추가됨 - jQuery를 사용하는 경우 Google 사양을 다음과 동일한 정확한 오류가 발생하면 am>을 볼 수 있습니다.

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    data: { "longUrl": "http://www.google.com/" },
    url: "https://www.googleapis.com/urlshortener/v1/url",
    success: function(data) {
        //do something with the shortened url json data
        //console.log(data);
    }
});
.

도움이 되었습니까?

해결책

여기에 해결책이 있습니다 (@greg의 코멘트는 올바른 방향으로 나를 가리키는 것)입니다.

var xmlHttp = new XMLHttpRequest();

xmlHttp.open("POST", "https://www.googleapis.com/urlshortener/v1/url", true);
xmlHttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");

var req = new Object();
req.longUrl = "http://www.google.com/";

var jsonStr = JSON.stringify(req);

xmlHttp.send(jsonStr);
.

다른 팁

Google이 제공하는 사양을 따르지 않습니다.JSON 객체를 다음과 같이 보내야합니다 :

{"longUrl": "http://www.google.com/"}
.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top