Sending data through POST request from a node.js server to a node.js server

前端 未结 2 1782
闹比i
闹比i 2020-12-04 08:35

I\'m trying to send data through a POST request from a node.js server to another node.js server. What I do in the \"client\" node.js is the following:



        
2条回答
  •  星月不相逢
    2020-12-04 09:21

    Posting data is a matter of sending a query string (just like the way you would send it with an URL after the ?) as the request body.

    This requires Content-Type and Content-Length headers, so the receiving server knows how to interpret the incoming data. (*)

    var querystring = require('querystring');
    var http = require('http');
    
    var data = querystring.stringify({
          username: yourUsernameValue,
          password: yourPasswordValue
        });
    
    var options = {
        host: 'my.url',
        port: 80,
        path: '/login',
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': Buffer.byteLength(data)
        }
    };
    
    var req = http.request(options, function(res) {
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            console.log("body: " + chunk);
        });
    });
    
    req.write(data);
    req.end();
    

    (*) Sending data requires the Content-Type header to be set correctly, i.e. application/x-www-form-urlencoded for the traditional format that a standard HTML form would use.

    It's easy to send JSON (application/json) in exactly the same manner; just JSON.stringify() the data beforehand.

    URL-encoded data supports one level of structure (i.e. key and value). JSON is useful when it comes to exchanging data that has a nested structure.

    The bottom line is: The server must be able to interpret the content type in question. It could be text/plain or anything else; there is no need to convert data if the receiving server understands it as it is.

    Add a charset parameter (e.g. application/json; charset=Windows-1252) if your data is in an unusual character set, i.e. not UTF-8. This can be necessary if you read it from a file, for example.

提交回复
热议问题