如何使用node.js发布到请求 [英] How to post to a request using node.js

查看:100
本文介绍了如何使用node.js发布到请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一些json发布到URL。我在stackoverflow上看到了关于这个的各种其他问题,但它们似乎都没有明确或有效。这是我得到了多远,我在api文档上修改了示例:

I am trying to post some json to a URL. I saw various other questions about this on stackoverflow but none of them seemed to be clear or work. This is how far I got, I modified the example on the api docs:

var http = require('http');
var google = http.createClient(80, 'server');
var request = google.request('POST', '/get_stuff',
  {'host': 'sever',  'content-type': 'application/json'});
request.write(JSON.stringify(some_json),encoding='utf8'); //possibly need to escape as well? 
request.end();
request.on('response', function (response) {
  console.log('STATUS: ' + response.statusCode);
  console.log('HEADERS: ' + JSON.stringify(response.headers));
  response.setEncoding('utf8');
  response.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

当我发布到服务器时,我收到一个错误,告诉我它不是json格式或者这不是utf8,他们应该是。我试图拉取请求网址,但它是null。我刚开始使用nodejs所以请你好。

When I post this to the server I get an error telling me that it's not of the json format or that it's not utf8, which they should be. I tried to pull the request url but it is null. I am just starting with nodejs so please be nice.

推荐答案

问题是你在错误的地方设置Content-Type 。它是请求标头的一部分,它在options对象中有自己的密钥,这是request()方法的第一个参数。这是使用ClientRequest()进行一次性事务的实现(如果需要与同一服务器建立多个连接,可以保留createClient()):

The issue is that you are setting Content-Type in the wrong place. It is part of the request headers, which have their own key in the options object, the first parameter of the request() method. Here's an implementation using ClientRequest() for a one-time transaction (you can keep createClient() if you need to make multiple connections to the same server):

var http = require('http')

var body = JSON.stringify({
    foo: "bar"
})

var request = new http.ClientRequest({
    hostname: "SERVER_NAME",
    port: 80,
    path: "/get_stuff",
    method: "POST",
    headers: {
        "Content-Type": "application/json",
        "Content-Length": Buffer.byteLength(body)
    }
})

request.end(body)

其余的问题中的代码是正确的(request.on()及以下)。

The rest of the code in the question is correct (request.on() and below).

这篇关于如何使用node.js发布到请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆