2014-10-14 7 views
0

node.js를 사용하여 다른 응용 프로그램 (localhost : 3000에서 실행중인)의 데이터 메소드를 호출하려고합니다. 그러나 그 반환 오류가 .. node.js + 게시물 요청

다음

코드입니다 :

var options = { 
    host: 'localhost', 
    path: '/v1/key/11111111', 
    //since we are listening on a custom port, we need to specify it by hand 
    port: '3000', 
    //This is what changes the request to a POST request 
    method: 'POST', 
    headers: {'Content-Type': 'application/json'} 
}; 

callback = function(response) { 
    var str = '' 
    response.on('data', function (chunk) { 
    str += chunk; 
    }); 

    response.on('end', function() { 
    console.log(str); 
    }); 
} 

var req = http.request(options, callback); 
//This is the data we are posting, it needs to be a string or a buffer 
req.write("hello world!"); 
req.end(); 

하지만 난 오류가 발생하고있다 :

{"meta":{"version":1,"status_code":400},"results":{"error":{"type":"Error","message":"invalid json"}}} 

내가 원하는 결과를 얻고있다 CURL 명령을 사용하려합니다 :

curl -X POST localhost:3000/v1/key/12345678 --header "Content-Type:application/json" 

제 질문은 어떻게 구성해야합니까? POST request for the above requirement.

답변

3

요청 옵션에 'application/json'을 지정하십시오. 하지만 "Hello world!"라는 문자열을 제공합니다.이 문자열은 json이 아니며 오류 메시지가 알려줍니다.

헤더 또는 내용을 변경해보십시오.

+0

고맙습니다. 빈 json {}을 보내고 싶습니다. 내가해야 할 일은 .. req.write ({})를 시도했습니다. 나는 새로운 TypeError ('첫 번째 인수는 문자열 또는 버퍼 여야 함')를 던져서 오류를받습니다. – Subburaj

+0

유효한 json을 문자열로 보내야합니다. 다음을 시도해보십시오. req.write ("{}"); – Gustav