[node.js] Content-Type : application / json post with node.js 보내기

NodeJS에서 이와 같은 HTTP 요청을 어떻게 만들 수 있습니까? 예 또는 모듈 감사합니다.

curl https://www.googleapis.com/urlshortener/v1/url \
  -H 'Content-Type: application/json' \
  -d '{"longUrl": "http://www.google.com/"}'



답변

Mikeal의 요청 모듈은이를 쉽게 수행 할 수 있습니다.

var request = require('request');

var options = {
  uri: 'https://www.googleapis.com/urlshortener/v1/url',
  method: 'POST',
  json: {
    "longUrl": "http://www.google.com/"
  }
};

request(options, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body.id) // Print the shortened url.
  }
});


답변

간단한 예

var request = require('request');

//Custom Header pass
var headersOpt = {
    "content-type": "application/json",
};
request(
        {
        method:'post',
        url:'https://www.googleapis.com/urlshortener/v1/url',
        form: {name:'hello',age:25},
        headers: headersOpt,
        json: true,
    }, function (error, response, body) {
        //Print the Response
        console.log(body);
}); 


답변

현상태대로 공식 문서 말한다 :

body-PATCH, POST 및 PUT 요청에 대한 엔티티 본문입니다. 버퍼, 문자열 또는 ReadStream이어야합니다. json이 true이면 body는 JSON 직렬화 가능 객체 여야합니다.

JSON을 보낼 때 옵션 본문에 넣어야합니다.

var options = {
    uri: 'https://myurl.com',
    method: 'POST',
    json: true,
    body: {'my_date' : 'json'}
}
request(options, myCallback)


답변

어떤 이유로 오늘은 이것이 저에게 효과적이었습니다. 다른 모든 변형은 잘못된 json으로 끝났습니다. API 오류로 .

게다가 JSON 페이로드로 필요한 POST 요청을 생성하는 또 다른 변형입니다.

request.post({
    uri: 'https://www.googleapis.com/urlshortener/v1/url',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({"longUrl": "http://www.google.com/"})
});


답변

헤더 및 게시물과 함께 요청 사용.

var options = {
            headers: {
                  'Authorization': 'AccessKey ' + token,
                  'Content-Type' : 'application/json'
            },
            uri: 'https://myurl.com/param' + value',
            method: 'POST',
            json: {'key':'value'}
 };

 request(options, function (err, httpResponse, body) {
    if (err){
         console.log("Hubo un error", JSON.stringify(err));
    }
    //res.status(200).send("Correcto" + JSON.stringify(body));
 })


답변

request다른 답변이 사용 하는 모듈이 더 이상 사용되지 않았 으므로 다음으로 전환하는 것이 좋습니다 node-fetch.

const fetch = require("node-fetch")

const url = "https://www.googleapis.com/urlshortener/v1/url"
const payload = { longUrl: "http://www.google.com/" }

const res = await fetch(url, {
  method: "post",
  body: JSON.stringify(payload),
  headers: { "Content-Type": "application/json" },
})

const { id } = await res.json()


답변