http模块(带有browserify的node.js)不使用方法PATCH写入请求体

时间:2022-12-20 16:58:59

I've been developing a web client to interact with a REST API server, and would like to use PATCH method.

我一直在开发一个与REST API服务器交互的Web客户端,并且想要使用PATCH方法。

Although I've tried to write a request body into PATCH's request, I found the body remains empty. PUT or POST works fine in the same way though.

虽然我试图在PATCH的请求中写一个请求体,但我发现身体仍然是空的。虽然PUT或POST以同样的方式工作正常。

I can use PUT instead, but does anyone know if my usage of http module is wrong?

我可以使用PUT,但有人知道我的http模块使用是否错误?

Thank you in advance.

先感谢您。

var http = require('http');

module.exports = {

  patch: function(path, data, done, fail){
    var jsonData = JSON.stringify(data);
    var options = {
      headers: {
        'Content-Type':'application/json;charset=UTF-8',
        'Content-Length':jsonData.length,
      }
    };
    var req = this.request(path, "PATCH", done, fail, options);

    // THIS CODE DOESN'T WRITE jsonData INTO REQUEST BODY
    req.write(jsonData);
    req.end();
  },

  request: function(path, method, done = () => {}, fail = () => {}, options = { headers: {} } ){
    options.path = path;
    options.method = method;
    return http.request(options, function(res){
      var body = '';
      res.setEncoding('utf8');
      res.on("data", function(chunk){
        body += chunk;
      });
      res.on("end", function(){
        // process after receiving data from server
      });
    }).on("error", function(e) {
      // process after receiving error
    });
  }
}

2 个解决方案

#1


1  

I ended up using the "request" library for node.js. Following code works:

我最终使用了node.js的“请求”库。以下代码有效:

var request = require("request");
(...)

function patch(path, entity){
    var deferred = q.defer();     
    var escapedPath = escapeSpaces(path);
    AuthProvider.retrieveToken().done(function (authToken){
        var headers ={
            'OData-MaxVersion': '4.0',
            'OData-Version': '4.0',
            'Content-Type': 'application/json; charset=utf-8',
            'Authorization': 'Bearer '+ authToken,
            'Accept': 'application/json'     
        }

        var options = {
            url: "https://"+resourceApiId+"/api/data/v8.0/"+escapedPath,
            method: 'PATCH',
            headers: {
                'OData-MaxVersion': '4.0',
                "OData-Version": '4.0',
                "Content-Type": "application/json; charset=utf-8",
                "Authorization": 'Bearer '+ authToken,
                "Accept": "application/json"                
            },
            json: entity      
        };  

        request(options, function(error, response, body){
                if (!error) {
                    console.log("patchrequest statuscode: "+response.statusCode )
                    deferred.resolve(true);
                }
                deferred.reject(error);
            }
        );
    });

    return deferred.promise;
}

#2


1  

I have the very same problem with this code:

我对此代码有同样的问题:

function patch(path, entity){
    var deferred = q.defer();     
    var escapedPath = escapeSpaces(path);
    var stringEntity = JSON.stringify(entity);
    AuthProvider.retrieveToken().done(function (authToken){
        var options = {
            host: resourceApiId,
            path: "/api/data/v8.0/"+escapedPath,
            method: 'PATCH',
            headers: {
                'OData-MaxVersion': '4.0',
                "OData-Version": '4.0',
                "Content-Type": "application/json; charset=utf-8",
                "Authorization": 'Bearer '+ authToken,
                "Accept": "application/json"
            }       
        };  

        var reqToCrm = https.request(options, function(resFromCrm){
            var body = '';
            resFromCrm.on('data', function(d) {
                body += d;
            });
            resFromCrm.on('end', function() {
                try{
                    var parsed = JSON.parse(body);
                    if(parsed.error){
                        var errorString = "webApiRequest.js/patch: An error returned from CRM: " + parsed.error.message + "\n"
                        +"Body Returned from CRM: " + body;
                        console.log(errorString);
                        deferred.reject(errorString);
                    }
                    deferred.resolve(parsed);
                }
                catch (error){
                    var errorString = "Error parsing the response JSON from CRM.\n"
                    +"Parse Error: " + error.message + "\n"
                    +"Response received: "+ body;
                    console.log(errorString);
                    deferred.reject(errorString);
                }

            });            
        });

        reqToCrm.on('error', function(error) {
            console.log(error.message);
            deferred.reject("webApiRequest.js/post: Error returned on 'PATCH' against CRM \n" + error.message);
        });

        reqToCrm.write(stringEntity);
        reqToCrm.end(); 
    });

    return deferred.promise;
}

I Also already tried making a POST request and setting 'X-HTTP-Method-Override': 'PATCH. Did not work either. I can not use any other Request method as Dynamics CRM forbids it.

我也尝试过发出POST请求并设置'X-HTTP-Method-Override':'PATCH。也没用。我不能使用任何其他Request方法,因为Dynamics CRM禁止它。

#1


1  

I ended up using the "request" library for node.js. Following code works:

我最终使用了node.js的“请求”库。以下代码有效:

var request = require("request");
(...)

function patch(path, entity){
    var deferred = q.defer();     
    var escapedPath = escapeSpaces(path);
    AuthProvider.retrieveToken().done(function (authToken){
        var headers ={
            'OData-MaxVersion': '4.0',
            'OData-Version': '4.0',
            'Content-Type': 'application/json; charset=utf-8',
            'Authorization': 'Bearer '+ authToken,
            'Accept': 'application/json'     
        }

        var options = {
            url: "https://"+resourceApiId+"/api/data/v8.0/"+escapedPath,
            method: 'PATCH',
            headers: {
                'OData-MaxVersion': '4.0',
                "OData-Version": '4.0',
                "Content-Type": "application/json; charset=utf-8",
                "Authorization": 'Bearer '+ authToken,
                "Accept": "application/json"                
            },
            json: entity      
        };  

        request(options, function(error, response, body){
                if (!error) {
                    console.log("patchrequest statuscode: "+response.statusCode )
                    deferred.resolve(true);
                }
                deferred.reject(error);
            }
        );
    });

    return deferred.promise;
}

#2


1  

I have the very same problem with this code:

我对此代码有同样的问题:

function patch(path, entity){
    var deferred = q.defer();     
    var escapedPath = escapeSpaces(path);
    var stringEntity = JSON.stringify(entity);
    AuthProvider.retrieveToken().done(function (authToken){
        var options = {
            host: resourceApiId,
            path: "/api/data/v8.0/"+escapedPath,
            method: 'PATCH',
            headers: {
                'OData-MaxVersion': '4.0',
                "OData-Version": '4.0',
                "Content-Type": "application/json; charset=utf-8",
                "Authorization": 'Bearer '+ authToken,
                "Accept": "application/json"
            }       
        };  

        var reqToCrm = https.request(options, function(resFromCrm){
            var body = '';
            resFromCrm.on('data', function(d) {
                body += d;
            });
            resFromCrm.on('end', function() {
                try{
                    var parsed = JSON.parse(body);
                    if(parsed.error){
                        var errorString = "webApiRequest.js/patch: An error returned from CRM: " + parsed.error.message + "\n"
                        +"Body Returned from CRM: " + body;
                        console.log(errorString);
                        deferred.reject(errorString);
                    }
                    deferred.resolve(parsed);
                }
                catch (error){
                    var errorString = "Error parsing the response JSON from CRM.\n"
                    +"Parse Error: " + error.message + "\n"
                    +"Response received: "+ body;
                    console.log(errorString);
                    deferred.reject(errorString);
                }

            });            
        });

        reqToCrm.on('error', function(error) {
            console.log(error.message);
            deferred.reject("webApiRequest.js/post: Error returned on 'PATCH' against CRM \n" + error.message);
        });

        reqToCrm.write(stringEntity);
        reqToCrm.end(); 
    });

    return deferred.promise;
}

I Also already tried making a POST request and setting 'X-HTTP-Method-Override': 'PATCH. Did not work either. I can not use any other Request method as Dynamics CRM forbids it.

我也尝试过发出POST请求并设置'X-HTTP-Method-Override':'PATCH。也没用。我不能使用任何其他Request方法,因为Dynamics CRM禁止它。