Javascript 如何使用 node.js 发布到请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4505809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:41:15  来源:igfitidea点击:

How to post to a request using node.js

javascriptnode.jshttp-post

提问by Mr JSON

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:

我正在尝试将一些 json 发布到 URL。我在 stackoverflow 上看到了关于这个的各种其他问题,但似乎没有一个是清楚的或有效的。这就是我得到的程度,我修改了 api 文档上的示例:

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

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.

当我将其发布到服务器时,我收到一条错误消息,告诉我它不是 json 格式,或者不是 utf8,它们应该是。我试图拉请求 url 但它是空的。我刚开始使用 nodejs,所以请保持友好。

回答by Ankit Aggarwal

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):

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

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)

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

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

回答by Jonathan O'Connor

Jammus got this right. If the Content-Length header is not set, then the body will contain some kind of length at the start and a 0 at the end.

贾姆斯做对了。如果未设置 Content-Length 标头,则正文将在开头包含某种长度,在结尾包含 0。

So when I was sending from Node:

所以当我从 Node 发送时:

{"email":"[email protected]","passwd":"123456"}

my rails server was receiving:

我的 rails 服务器收到:

"2b {"email":"[email protected]","passwd":"123456"} 0  "

Rails didn't understand the 2b, so it wouldn't interpret the results.

Rails 不理解 2b,所以它不会解释结果。

So, for passing params via JSON, set the Content-Type to application/json, and always give the Content-Length.

因此,要通过 JSON 传递参数,请将 Content-Type 设置为 application/json,并始终提供 Content-Length。

回答by molokoloco

To send JSON as POST to an external API with NodeJS... (and "http" module)

使用 NodeJS 将 JSON 作为 POST 发送到外部 API...(和“http”模块)

var http = require('http');

var post_req  = null,
    post_data = '{"login":"toto","password":"okay","duration":"9999"}';

var post_options = {
    hostname: '192.168.1.1',
    port    : '8080',
    path    : '/web/authenticate',
    method  : 'POST',
    headers : {
        'Content-Type': 'application/json',
        'Cache-Control': 'no-cache',
        'Content-Length': post_data.length
    }
};

post_req = http.request(post_options, function (res) {
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log('Response: ', chunk);
    });
});

post_req.on('error', function(e) {
    console.log('problem with request: ' + e.message);
});

post_req.write(post_data);
post_req.end();

回答by Dio Phung

There is a very good library that support sending POST request in Nodejs:

有一个非常好的库支持在 Nodejs 中发送 POST 请求:

Link: https://github.com/mikeal/request

链接:https: //github.com/mikeal/request

Sample code:

示例代码:

var request = require('request');

//test data
var USER_DATA = {
    "email": "[email protected]",
    "password": "a075d17f3d453073853f813838c15b8023b8c487038436354fe599c3942e1f95"
}

var options = {
    method: 'POST',
    url: 'URL:PORT/PATH',
    headers: {
        'Content-Type': 'application/json'
    },
    json: USER_DATA

};


function callback(error, response, body) {
    if (!error) {
        var info = JSON.parse(JSON.stringify(body));
        console.log(info);
    }
    else {
        console.log('Error happened: '+ error);
    }
}

//send request
request(options, callback);

回答by jammus

Try including the content length.

尝试包括内容长度。

var body = JSON.stringify(some_json);
var request = google.request('POST', '/get_stuff', { 
    host: 'server',
    'Content-Length': Buffer.byteLength(body),
    'Content-Type': 'application/json' 
    });
request.write(body);
request.end();

回答by RandomEtc

This might not solve your problem, but javascript doesn't support named arguments, so where you say:

这可能无法解决您的问题,但 javascript 不支持命名参数,所以您说:

request.write(JSON.stringify(some_json),encoding='utf8');

You should be saying:

你应该说:

request.write(JSON.stringify(some_json),'utf8');

The encoding= is assigning to a global variable, so it's valid syntax but probably not doing what you intend.

encoding= 正在分配给一个全局变量,因此它是有效的语法,但可能没有按照您的意愿行事。

回答by jbmusso

Probably non-existent at the time this question was asked, you could use nowadays a higher level library for handling http requests, such as https://github.com/mikeal/request. Node's built-in http module is too low level for beginners to start with.

在问这个问题时可能不存在,现在您可以使用更高级别的库来处理 http 请求,例如https://github.com/mikeal/request。Node 内置的 http 模块对于初学者来说太低级了。

Mikeal's request module has built-in support for directly handling JSON (see the documentation, especially https://github.com/mikeal/request#requestoptions-callback).

Mikeal 的 request 模块内置支持直接处理 JSON(请参阅文档,尤其是https://github.com/mikeal/request#requestoptions-callback)。

回答by Jasper Fu

var request = google.request(
  'POST',
  '/get_stuff',
  {
    'host': 'sever',
    **'headers'**:
    {
      'content-type': 'application/json'
    }
  }
);