Pass data using the post method in json format. NodeJS


JSON (JavaScript Object Notation) is a format for exchanging data in text form. Allowing the transfer of complex data structures in serialized form. This data transfer format has become so popular that already in the PHP core, starting with version 5.2.0, functions for processing data in this format were added. This means that there is no need to connect additional extensions. The JSON data format is highly human-readable. In addition, this type of data exchange is widely used between various API services. And with the correct development of algorithms for information exchange, you can get a very high speed increase than, for example, when working with data in XML format.

Sending data

There are two ways to send data in JSON format: form a GET or POST request with encoded data located in a GET or POST variable, or place the data in the body of the document. In practice, the second option is usually used.

To send data, the following functions are required:

  • string json_encode(mixed value [, int options = 0 ])

    The value parameter specifies the data that needs to be encoded. Any type is supported except type resource. The options parameter contains a bitmask of the possible provided values ​​(see the table with provided JSON constants).

  • resource stream_context_create (])

    This function is designed to create and return a thread context with the options specified in the options parameter. The optional options parameter must be of type associative array. Initially, it is empty. The second optional params parameter must also be an associative array in the format $data['name'] = value.

  • string file_get_contents(string filename [, bool use_include_path [, resource context [, int offset [, int maxlen ]]]])

    Using this function allows you to get the contents of a file as a string. The filename parameter is the name of the file to read. In the use_include_path parameter, starting from PHP 5, you can use the constant FILE_USE_INCLUDE_PATH to search for a file in the include path. The context parameter represents the context resource created using the stream_context_create() function. If the attempt to open the file fails, the value will be returned false. The offset parameter contains the offset from which data reading will begin. The maxlen parameter specifies the size of the data received.

    Note: The offset is not specified when working with remote threads.

Below is an example of sending data in JSON format:

// Data to send $request = array("StartDate" => "2013-10-10", "EndDate" => "2013-10-10", "IDS" => array(1,2,3,4 ,5,6,7)); // Specifying options for the stream context $options = array ("http" => array ("method" => "POST", "header" => "Content-Type: application/json; charset=utf-8\r\ n", "content" => json_encode($request))); // Create a stream context $context = stream_context_create($options); // Sending data and getting the result echo file_get_contents("http://test.ru/json.php", 0, $context);

Here an improvised data structure is used, consisting of a start and end date, as well as an array of numbers of some conditional records. Please note that in the request header Content-Type the type “application/json” is specified.

Receiving data

In order to receive the transmitted data in the manner described above, it is necessary to read data from the input stream “ php://input”.

Functions used to accept data:

  • mixed json_decode(string json [, bool assoc = false [, int depth = 512 [, int options = 0 ]]])

    This function decodes a string in JSON format. The json parameter specifies the string to decode. The assoc parameter controls whether the returned data will be converted to an associative array. If there is such a need, then you must specify as the value of this parameter true. The depth parameter indicates the recursion depth. And the last fourth parameter, options, contains a bitmask of options for decoding. Currently only supported JSON_BIGINT_AS_STRING(by default, large integers are converted to floating point numbers (float))

  • resource fopen(string filename , string mode [, bool use_include_path [, resource context ]])

    Opens a file and returns its handle. The filename parameter is a named resource pointing to a file. The mode parameter specifies the type of file access (see the table with a list of possible modes for fopen()). Next are two optional parameters: use_include_path and context . When setting use_include_path to true or 1 and provided that a relative path is specified as a named resource, the file to be opened will be searched in the list of directories used by the functions include And require. In practice, this parameter is practically not used. The context parameter is used to specify the context of the resource.

  • string stream_get_contents(resource handle [, int maxlen = -1 [, int offset = -1 ]])

    This function allows you to get the contents of a stream as a string. The handle parameter is a thread resource. The maxlen parameter contains the maximum number of bytes to read. By default it is set to -1, which indicates that all data is received. The offset parameter contains the offset from which data reading will begin. By default it is also set to -1, which means that reading will be done from the starting position.

Below is an example of receiving data in JSON format on the server side:

// Open the input stream for reading $f = fopen("php://input", "r"); // Get the contents of the stream $data = stream_get_contents($f); if ($data) ( // Processing code print_r(json_decode($data)); )

The resulting data structure:

StdClass Object ( => 2013-10-10 => 2013-10-10 => Array ( => 1 => 2 => 3 => 4 => 5 => 6 => 7))

Note: It is necessary to take into account the fact that to work with the JSON format, the data must be encoded in utf-8.

JSON provided constants for the json_encode() function

JSON_HEX_TAG (integer) All are encoded in \u003C and \u003E. Available since PHP 5.3.0.
JSON_HEX_AMP (integer) All & are encoded in &. Available since PHP 5.3.0.
JSON_HEX_APOS (integer) All ' characters are encoded in \u0027. Available since PHP 5.3.0.
JSON_HEX_QUOT (integer) All " characters are encoded in \u0022. Available since PHP 5.3.0.
JSON_FORCE_OBJECT (integer) Return an object instead of an array when using a non-associative array. This is useful when the receiving program or code expects an object or the array is empty. Available since PHP 5.3.0.
JSON_NUMERIC_CHECK (integer) Encoding strings containing numbers as numbers. Available since PHP 5.3.3.
JSON_BIGINT_AS_STRING (integer) Encodes large integers as their string equivalents. Available since PHP 5.4.0.
JSON_PRETTY_PRINT (integer) Use whitespace characters in the returned data to format it. Available since PHP 5.4.0.
JSON_UNESCAPED_SLASHES (integer) Do not escape /. Available since PHP 5.4.0.
JSON_UNESCAPED_UNICODE (integer) Do not encode multibyte Unicode characters (they are encoded as \uXXXX by default). Available since PHP 5.4.0.

List of possible modes for fopen() using mode

'r' Opens the file read-only; places the pointer at the beginning of the file.
'r+' Opens a file for reading and writing; places the pointer at the beginning of the file.
'w' Opens the file for writing only; places a pointer at the beginning of the file and truncates the file to zero length. If the file does not exist, it tries to create it.
'w+' Opens a file for reading and writing; places a pointer at the beginning of the file and truncates the file to zero length. If the file does not exist, it tries to create it.
'a' Opens the file for writing only; places the pointer at the end of the file. If the file does not exist, it tries to create it.
'a+' Opens a file for reading and writing; places the pointer at the end of the file. If the file does not exist, it tries to create it.
'x' Creates and opens for writing only; places the pointer at the beginning of the file. If the file already exists, the fopen() call will fail, return FALSE, and throw an E_WARNING error. If the file does not exist, it will try to create it. This is equivalent to specifying the O_EXCL|O_CREAT flags for the internal open(2) system call.
'x+' Creates and opens for reading and writing; otherwise has the same behavior as 'x'.
'c' Opens the file for writing only. If the file does not exist, it is created. If the file exists, then it is not truncated (unlike 'w'), and calling this function does not cause an error (as in the case of 'x'). The file pointer will be set to the beginning of the file. This can be useful if you want to lock the file (see flock()) before changing it, since using 'w' can truncate the file before the lock has been acquired (if you want to truncate the file, you can use the ftruncate() function after requesting the lock ).
'c+' Opens a file for reading and writing; otherwise has the same behavior as 'c'.

I have a registration page to allow users to register. I need to confirm my phone number before registering. I have given the web service address along with its parameters.
the parameters I gave:

Http://********* Method:POST Headers:Content-Type:application/json Body: the following in: ( "mobileNo":"0*********", " service":"****", "Code1":"*****", "content":"hi", "actionDate":"2017/09/26", "requestId":"1")

and here is the code I found on the internet:

$data = array("mobileNo" => "****", "service" => "***", "Code1" => "*****", "content" => "55", "actionDate" => "2017/09/26"); $options = array("http" => array("method" => "POST", "content" => json_encode($data), "header"=> "Content-Type: application/json" . "Accept: application/json")); $url = "******"; $context = stream_context_create($options); $result = file_get_contents($url, false, $context); $response = json_decode($result);

and here is the error I encounter when I check for local:

File_get_contents(http://********/sms-gateway/sms-external-zone /receive): failed to open stream: A connection attempt failed because the connected party did not properly respond after a period of time , or established connection failed because connected host has failed to respond.

and there is no error and no result (receive SMS) in response when I test online (cpanel server)

Based on the given parameters, where am I wrong?

thank you in advance.

Solution

Based on your error, your service is not responding. Have you tried opening it in a browser to see if the answer is there?

It's possible that the service you're trying to call requires you to provide a static IP address from your web server, since they only provide IP-level access. This means your IP is blocked until they allow it.

I suggest you use cURL to fulfill your request. This way you have future data to debug if things don't work out. Also here, if the service is not responding, you want to get any other information.

$data = array("mobileNo" => "****", "service" => "***", "Code1" => "*****", "content" => "55", "actionDate" => "2017/09/26"); $url = "******"; $ch = curl_init($url); // set data as json string curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); // define json as content type curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/json")); // tell curl to fetch return data curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // follow location if redirect happens like http to https curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // send request $result = curl_exec($ch); // gives you the result - most of the time you only want this var_dump($result); // for debugging purpose, gives you the whole connection info var_dump(curl_getinfo($ch)); // gives back any errors occurred var_dump(curl_error($ch)); curl_close($ch);

I got a lot of information here so I wanted to post the solution I discovered.

Problem: Receiving JSON data from Javascript in the browser, on the server and using PHP to parse it successfully.

Wednesday: Javascript in browser (Firefox) on Windows. LAMP server as a remote server: PHP 5.3.2 on Ubuntu.

What works (version 1):
1) JSON is just text. Text in a specific format, but only a text string.

2) In Javascript, var str_json = JSON.stringify(myObject) gives me a JSON string.

3) I'm using an AJAX XMLHttpRequest object in Javascript to send data to the server:
request= new XMLHttpRequest()
request.open("POST", "JSON_Handler.php", true)
request.setRequestHeader("Content-type", "application/json")
request.send(str_json)
[... code to display response ...]

4) On the server PHP code to read the JSON string:
$str_json = file_get_contents("php://input");
This reads the raw POST data. $str_json now contains the exact JSON string from the browser.

What works (version 2):
1) If I want to use the "application/x-www-form-urlencoded" request header, I need to create a standard POST string "x=y&a=b" so that when PHP receives it, it can be placed in the $_POST associative array. So, in Javascript in the browser:

Var str_json = "json_string=" + (JSON.stringify(myObject))

Now PHP will be able to populate the $_POST array when I send str_json via AJAX/XMLHttpRequest like in version 1 above.

Displaying the contents of $_POST["json_string"] will display the JSON string. Using json_decode() on a $_POST array element with a json string will properly decode that data and put it into an array/object.

The pitfall I encountered:
I initially tried to send a JSON string with the application header /x -www-form-urlencoded and then tried to immediately read it from the $_POST array in PHP. The $_POST array was always empty. This is because it expects data of the form yval = xval & . It found no such data, just a JSON string, and it just threw it away. I looked at the request headers and the POST data was sent correctly.

Likewise, if I use the application/json header, I again cannot access the data being sent via the $_POST array. If you want to use the application/json content header, then you must access the raw POST data in PHP via the php:// input rather than with $_POST.

Literature:
1) How to access POST data in PHP: How to access POST data in PHP?
2) Details of the application/json type with some example objects that can be converted to JSON strings and sent to the server:

How to send Ajax a list of objects (List) in JSON format

Example 1

$(document).ready(function () ( $("body").on("click", "button", function () ( var product = JSON.stringify(( "Name": $("textarea") .val(), "Cost": $("input").val(), )); console.log(product); $.ajax(( url: "/Products/AjaxCreate/", method: "POST" , contentType: "application/json", data: product, success: function (response) ( console.log(response); ) )); )); ));

Controller

Public ActionResult AjaxCreate(Product product)( return Json(new ( result = "success"), JsonRequestBehavior.AllowGet); )

Example 2

//Saving the invoice$("body").on("click", "button", function () ( //Assemble the table as an array of objects var billDetails = ; $(".item").each(function () ( var name = $(this).find(".name").val(); //Name var quantity = parseInt($(this).find(" .quantity").val()); //Quantity var price = parseFloat($(this).find(".price").val());//Price var summ = parseFloat($(this).find (".item-summ").attr("value"));//Sum var productId = parseFloat($(this).find(".item-id").attr("value"));// Product Id var productSkuId = parseInt($(this).find(".item-sku-id").attr("value")); //Id of the Product Trade Offer var notRec = $(this).find(".item-not-rec").prop("checked"); //Take the product into account or not billDetails.push(( Name: name, Quantity: quantity, Price: price, Summ: summ, ProductId: productId, ProductSkuId: productSkuId, NotRec: notRec )); )); console.log(billDetails); billDetails = JSON.stringify(( "billDetails": billDetails )); //Turn into Statham //Send for saving$.ajax(( url: "/Bills/AjaxSaveInvoiceBill/", method: "POST", contentType: "application/json", data: billDetails, success: function (response) ( window.location.replace("/Bills/ List/"); ) )); return false; ));

Controller

Public ActionResult AjaxSaveInvoiceBill(List billDetails)( if (billDetails.Count == 0) return Json(new ( result = "error", message = "There are no goods in the invoice"), JsonRequestBehavior.AllowGet); //Create a new invoice and get its ID long billId = Bill.CreateBill(BillTypes.Invoice); //Now let's save each position under the ID of the new invoice BillDetail.SaveBillDetails(billDetails, billId); return Json(new ( result="success", message="Invoice created successfully" ), JsonRequestBehavior.AllowGet); )

Ajax request to controller and receiving Json response

$(document).ready(function () ( $.ajax(( url: "/Suppliers/AjaxGetSuppliersList/", method: "GET", success: function (response) ( data = JSON.stringify(response.suppliers); var list = eval("(" + data + ")"); suggest_count = list.length; if (suggest_count > 0) ( $(".supplier-select").empty(); //Clear the list of elements //add the resulting list of elements to the select$.each(response.suppliers, function (key, value) ( ​​$(".supplier-select").append(" "); }); } } }); });

Controller

Public ActionResult AjaxGetSuppliersList() ( List suppliers = Supplier.GetSuppliers(); return Json(new ( suppliers ), JsonRequestBehavior.AllowGet); )

Hi all! In this article we will look at, how to send data to client in JSON format in NodeJS.

Introduction

In the last article we looked at how to send HTML pages to the client using streams in NodeJS. Today we will look at how to send data in the format JSON.

We won't be using threads to solve this problem, so you can remove all thread-related code. Instead we will use end() a method that is already familiar to us and was used in one of the previous articles.

How to send JSON

First of all, we need to change the header so that the browser can process our data correctly:

Res.writeHead(200, ("Content-Type": "application/json"));

Now let's create the object that we want to send to the client:

Var myObj = (
name: "John",
job: "programmer",
age: 27
};

Now let's send the data to the client:

Res.end(myObj);

But in reality, such code will not work correctly. The point is that the method end() expects to see data in string or buffer format. We have an object, but we can make a string out of it like this:

Res.end(JSON.stringify(myObj));

Now, if you run the application, you will see that the data has arrived in JSON format as a string. You can also use the developer tools in your browser and see that the header has also been set correctly.

Why send JSON data to the client

You may have a question: why send data to the client at all? JSON format. To answer this question, imagine that you have some javascript executing on the client side( frontend), and it can create some query. For example, you have API. You can write the following query:

Localhost:3000/api/request

And the server will have to send us data for this request. It will be most convenient to send them in the format JSON, so that the script running on the client side can then easily process this data.

Conclusion

So today we looked at, how to send data to client in JSON format in NodeJS.







2024 gtavrl.ru.