source

content-Type: application/js를 node.js와 함께 게시합니다.

ittop 2023. 8. 15. 11:42
반응형

content-Type: application/js를 node.js와 함께 게시합니다.

NodeJS에서 어떻게 이런 HTTP 요청을 할 수 있습니까?예시 또는 모듈 감사합니다.

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

미칼레 의 모듈은 이를 쉽게 수행할 수 있습니다.

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

공식 문서에 언급된 바와 같이:

본문 - PATCH, POST 및 PUT 요청에 대한 엔티티 본문입니다.버퍼, 문자열 또는 읽기 스트림이어야 합니다.json이 참이면 본문은 JSON 직렬화 가능 개체여야 합니다.

JSON을 보낼 때는 옵션 본문에 넣으면 됩니다.

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

오늘은 웬일인지 이것만 효과가 있었습니다.다른 모든 변형은 API에서 불량 json 오류로 끝났습니다.

게다가, 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/"})
});

Axios는 더 작고 더 우수합니다.

const data = JSON.stringify({
  message: 'Hello World!'
})

const url = "https://localhost/WeatherAPI";

axios({
    method: 'POST',
    url, 
    data: JSON.stringify(data), 
    headers:{'Content-Type': 'application/json; charset=utf-8'}
}) 
  .then((res) => {
    console.log(`statusCode: ${res.status}`)
    console.log(res)
  })
  .catch((error) => {
    console.error(error)
  })

Node.js에서 HTTP 요청을 만드는 5가지 방법도 확인합니다.

https://www.twilio.com/blog/2017/08/http-requests-in-node-js.html

참조:

https://nodejs.dev/learning/make-an-make-an-post-request-using-nodejs

https://flaviocopes.com/node-http-post/

https://stackabuse.com/making-asynchronous-http-requests-in-javascript-with-axios/

그 이후로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()

헤더 및 게시물과 함께 요청을 사용합니다.

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

언급URL : https://stackoverflow.com/questions/8675688/send-content-type-application-json-post-with-node-js

반응형