gpt4 book ai didi

node.js - 如何使用 Node.js http 客户端进行 POST?

转载 作者:搜寻专家 更新时间:2023-11-01 00:10:52 26 4
gpt4 key购买 nike

我正在尝试按照此处的文档

http://nodejs.org/api/http.html

但我找不到有关执行一些简单操作(例如将用户名和密码发布到 URL)的文档。我该怎么做?

最佳答案

node.js 文档对此不是特别清楚

http://nodejs.org/api/http.html#http_http_request_options_callback

这就是我发出请求的方式,使用查询字符串来解析输入。

//require a few things.

var http = require('http'),
qs = require('qs');

//These are the post options
var options = {
hostname: 'www.mysite.com',
port: 80,
path: '/auth',
method: 'POST'
};
//The postdata can be anything, but I'm using querystring
//to convert it into the format
//username=User&password=Password to be easily parsed in php

var postdata = qs.stringify({
username:"User",
password:"Password"
});

//Initialise the variable that will store the response
var body='';


//Now we're going to set up the request and the callbacks to handle the data
var request = http.request(options, function(response) {
//When we receive data, we want to store it in a string
response.on('data', function (chunk) {
body += chunk;
});
//On end of the request, run what we need to
response.on('end',function() {
//Do Something with the data
console.log(body);
});
});

//Now we need to set up the request itself.
//This is a simple sample error function
request.on('error', function(e) {
console.log('problem with request: ' + e.message);
});


//Write our post data to the request
request.write(postdata);
//End the request.
request.end();

关于node.js - 如何使用 Node.js http 客户端进行 POST?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10469412/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com