Just learn Nodejs, do an example: send a simple HTTP request. Encountered a problem, the client sent to the service side of the message to the server, the server received no message, the exact word is "".
Here is the server-side code: Server.js
Const HTTP = require ("http"); const QS = require ("querystring") Http.createserver (function (request,response) { var BODY = ""; Request.on ("Data", function (chunk) { body+=chunk; }) Request.on ("End", function () { response.writehead (200,{"ContentType": "Text/html;charset=utf-8"}); Console.log (body) process.stdout.write ("Got name:" + qs.parse (body) ["name"]+ "\ n")}) }). Listen (3000);
The following is the client code:
var http = require ("http"); var qs = require ("querystring") var options = {hostname: ' 127.0.0.1 ', port:3000, path : '/', Method: ' POST ',};functionGetName (thename) {
var B = {Name:thename};
var A=qs.Stringify (b)
Console.Logtypeof thename)
Console.Log"Thename:" +thename+", b after conversion to string A:" +a);
Http.request (Options,Function (response) {
Response.setencoding (' UTF8 ');
var BODY = Response.on ( ' data ' Span style= "color: #cc7832; Font-weight:bold ">function (chunk) {
Body+=chunk;
) Response.on ( ' end ' ,function () {
Process.stdout. Write ( "client Compate! \n }). end (a) } Correct code process.stdin.on ("Data", function (inputdata) {process.stdout.write ("Your Name:" +inputdata); Console.log ("Input:" +inputdata+ "converted to string:" +inputdata.tostring (). replace ("\ r \ n", ""))//inputdata has a carriage return getname ( Inputdata.tostring (). replace ("\ r \ n", ""));})
Error code
Process.stdin.on ("Data", function (inputdata) { process.stdout.write ("Your Name:" +inputdata); GetName (Inputdata);})
Server, there is no need to say more here. We see the client error code: Here, there is no inputdata processing for the "user input data" received, so the inputdata here is the object type;
See Client feedback results:
The return result of the service side:
The type of B has been viewed successively:
I believe the root of the problem is known here: The obtained parameter is a buffer type, resulting in parsing problems later. Then, when calling GetName, convert the parameters well. This logic should be workable.
But here I have a question, how to convert the received input object?
QueryString: Where there is a module in Nodejs, QueryString, the role is to parse the URL query string, there are stringify () and Parse () Two methods, one is a turn string, and the other is to parse the object;
JSON. Stringify () canparse the JSON string into string;
ToString () Method: Can parse to string
Here we are using the inputdata.tostring (). This is just a pass-through parameter, not a URL-related, naturally. Okay, problem solved!
The ToString () method of object in Nodejs QueryString Stringify () json.stringify ()