node中,post请求步骤

node    post请求

1                   var alldata = "";

2                   //下面是post请求接收的一个公式

3                   //node为了追求极致,它是一个小段一个小段接收的。

4                   //接受了一小段,可能就给别人去服务了。防止一个过大的表单阻塞了整个进程

5                   req.addListener("data",function(chunk){

6                       alldata += chunk;

7                   });

8                   //全部传输完毕

9                   req.addListener("end",function(){

10                   console.log(alldata.toString());

11                   res.end("success");

12               });

 

原生写POST处理,比较复杂,要写两个监听。文件上传业务比较难写。

所以,用第三方模块。formidable。

form.parse(req, function(err, fields, files) {
      res.writeHead(200, {'content-type': 'text/plain'});
      res.write('received upload:\n\n');
      res.end(util.inspect({fields: fields, files: files}));
    });
 
  
  }


 

只要涉及文件上传,那么form标签要加一个属性:

1           <form action="http://127.0.0.1/dopost" method="post"enctype="multipart/form-data">

/**
 * 修改上传的文件名
 */
var http = require("http");
var formidable = require('formidable');
var util = require("util");
var fs = require("fs");
var sd = require("silly-datetime");
var path = require("path");


//创建服务器
var server = http.createServer(function(req,res){
    //如果你的访问地址是这个,并且请求类型是post
    if(req.url == "/dopost" && req.method.toLowerCase() == "post"){
        //Creates a new incoming form.
        var form = new formidable.IncomingForm();
        //设置文件上传存放地址
        form.uploadDir = "./uploads";
        //执行里面的回调函数的时候,表单已经全部接收完毕了。
        form.parse(req, function(err, fields, files) {
            //if(err){
            //    throw err;
            //}
            //console.log(util.inspect({fields: fields, files: files}));

            //时间,使用了第三方模块,silly-datetime
            var ttt = sd.format(new Date(), 'YYYYMMDDHHmmss');
            var ran = parseInt(Math.random() * 89999 + 10000);
            var extname = path.extname(files.tupian.name);
            //执行改名
            var oldpath = __dirname + "/" + files.tupian.path;
            //新的路径由三个部分组成:时间戳、随机数、拓展名
            var newpath = __dirname + "/uploads/" + ttt + ran + extname;

            //改名
            fs.rename(oldpath,newpath,function(err){
                if(err){
                    throw Error("改名失败");
                }
                res.writeHead(200, {'content-type': 'text/plain'});
                res.end("成功");
            });
        });
    }else if(req.url == "/"){
        //呈递form.html页面
        fs.readFile("./form.html",function(err,data){
            res.writeHead(200, {'content-type': 'text/html'});
            res.end(data);
        })
    }else{
        res.writeHead(404, {'content-type': 'text/html'});
        res.end("404");
    }
});

server.listen(80,"192.168.41.36");


 

### 回答1: 好的,我可以用文为你讲解如何使用 Node.js 发送 HTTP GET 和 POST 请求。 首先,你需要安装 Node.js 和 npm(Node.js 包管理器)。然后,你可以使用 npm 安装 "request" 模块,这是一个简单易用的 HTTP 客户端库,可以让你轻松发送 HTTP 请求。 安装 "request" 模块的命令如下: ``` npm install request ``` 安装完成后,你就可以在 Node.js 代码引入 "request" 模块,并使用它发送 HTTP 请求了。 发送 HTTP GET 请求的代码如下: ``` const request = require('request'); request.get('http://www.example.com', (error, response, body) => { if (!error && response.statusCode == 200) { console.log(body); } }); ``` 发送 HTTP POST 请求的代码如下: ``` const request = require('request'); const options = { url: 'http://www.example.com', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, form: { key: 'value', }, }; request(options, (error, response, body) => { if (!error && response.statusCode == 200) { console.log(body); } }); ``` 希望这些信息能帮到你。 ### 回答2: 使用Node.js的http模块可以发送GET和POST请求。 发送GET请求步骤如下: 1. 首先,我们需要导入http模块,并创建一个服务器对象: ```javascript const http = require('http'); ``` 2. 然后,我们可以使用http模块的get方法发送GET请求: ```javascript const options = { hostname: 'example.com', path: '/api/some-endpoint', method: 'GET' }; const req = http.request(options, (res) => { res.on('data', (data) => { // 处理返回的数据 }); }); req.on('error', (error) => { // 处理请求错误 }); req.end(); ``` 在上面的代码,我们使用http.request方法创建一个请求对象。我们需要提供一个包含主机名(hostname)、路径(path)和请求方法(method)的选项(options)对象。然后,我们可以通过调用req.end()方法发送请求。当服务器返回数据时,我们可以通过监听'res'对象的'data'事件来处理数据,同时还可以监听'error'事件来处理请求错误。 发送POST请求步骤类似,只需要设置请求方法为POST,并提供请求体数据。以下是一个发送POST请求的例子: ```javascript const postData = JSON.stringify({ username: 'john', password: 'secret' }); const options = { hostname: 'example.com', path: '/api/login', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(postData) } }; const req = http.request(options, (res) => { res.on('data', (data) => { // 处理返回的数据 }); }); req.on('error', (error) => { // 处理请求错误 }); req.write(postData); req.end(); ``` 在上面的例子,我们设置了请求方法为POST,并提供了请求体数据,即postData。我们还设置了请求头(headers)来指定请求体数据的类型和长度。 以上就是使用Node.js的http模块发送GET和POST请求的基本步骤。 ### 回答3: 使用Node.js的http模块可以很方便地发送GET和POST请求。 发送GET请求步骤如下: 1. 首先需要引入http模块:const http = require('http'); 2. 创建一个http请求对象:const options = { hostname: 'www.example.com', // 请求目标的主机名 path: '/api/data', // 请求目标的路径 method: 'GET' // 请求方法为GET }; 3. 发送请求:const req = http.request(options, (res) => { // 处理响应 res.on('data', (data) => { console.log(data.toString()); }); }); req.end(); 发送POST请求步骤如下: 1. 引入http模块:const http = require('http'); 2. 创建一个http请求对象:const options = { hostname: 'www.example.com', // 请求目标的主机名 path: '/api/data', // 请求目标的路径 method: 'POST', // 请求方法为POST headers: { 'Content-Type': 'application/json' // 请求头设置为JSON格式 } }; 3. 创建一个POST请求体:const postData = JSON.stringify({name: 'John', age: 25}); 4. 发送请求:const req = http.request(options, (res) => { // 处理响应 res.on('data', (data) => { console.log(data.toString()); }); }); req.write(postData); // 将请求体写入请求 req.end(); 以上就是使用Node.js的http模块发送GET和POST请求的简单示例。根据具体需求,可以对请求头和请求体进行更多的定制。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值