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

Javascript 如何使用node.js发布到请求,javascript,node.js,http-post,Javascript,Node.js,Http Post,我正在尝试将一些json发布到URL。我在stackoverflow上看到了关于这一点的各种其他问题,但似乎没有一个是明确的或有效的。这就是我取得的成绩,我修改了api文档中的示例: var http = require('http'); var google = http.createClient(80, 'server'); var request = google.request('POST', '/get_stuff', {'host': 'sever', 'content-typ

我正在尝试将一些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);
  });
});

当我把它发布到服务器上时,我得到一个错误,告诉我它不是json格式,或者它不是utf8格式,它们应该是utf8格式。我试图提取请求url,但它为空。我只是从nodejs开始,所以请友好一些。

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

request.write(JSON.stringify(some_json),encoding='utf8');
你应该说:

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

encoding=正在分配给一个全局变量,因此它的语法是有效的,但可能没有达到您的目的。

尝试包含内容长度

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

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


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

Jammus做到了这一点。如果未设置内容长度标题,则正文将在开头包含某种长度,在结尾包含0

所以当我从Node发送时:

{"email":"joe@bloggs.com","passwd":"123456"}
我的rails服务器正在接收:

"2b {"email":"joe@bloggs.com","passwd":"123456"} 0  "
Rails不理解2b,因此它不会解释结果


因此,要通过JSON传递参数,请将内容类型设置为application/JSON,并始终给出内容长度。

在提出此问题时可能不存在,现在可以使用更高级别的库来处理http请求,例如。Node的内置http模块对于初学者来说级别太低了


Mikeal的请求模块内置了直接处理JSON的支持(特别是请参阅文档)。

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

链接:

示例代码:

var request = require('request');

//test data
var USER_DATA = {
    "email": "email@mail.com",
    "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);

要将JSON作为POST发送到带有NodeJS的外部API。。。(和“http”模块)


实际上,赋值的结果无论如何都是“utf8”,所以它可能正在做您想要做的事情:)“utf8”用于编码的参数无论如何都是过时的(默认值)您能发布实际的错误消息并从哪里得到它吗?从请求的服务器或node.js?我想“f**”是什么,但在设置了Content-Length头之后,api请求工作起来很有魅力。“总是给出内容长度。”非常感谢这一点,非常有用。请不要使用data.Length,我突然提到了这个问题,作者说不要使用data.Length,而是使用Buffer.bytellength(数据)。参考问题:和参考问题:相应地晚了一年更新。@Tobiq-视情况而定。关于什么时候可以假设ASCII是您所怀疑的,有很好的信息。通过远程通信,这是更简单的。。。不需要担心UTF8、UTF7或Unicode等。请不要使用data.length,我突然提到了这个问题,作者说不要使用data.length,而是使用Buffer.bytellength(数据)。参考问题:和参考问题:
"2b {"email":"joe@bloggs.com","passwd":"123456"} 0  "
var request = require('request');

//test data
var USER_DATA = {
    "email": "email@mail.com",
    "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);
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();