How does Node. js respond to Ajax POST requests and save them as JSON files?
Purpose
How can a front-end application developed using D3.js show the last interactive content of a graph after the user interacts with the graph to change its content?
This article provides a minimal solution through the back-end Node. js program as a reference.
Development Environment
- Backend: Node. js
- Node. js modules: Express, body-parser, fs
- Front-end: JQuery
Backend
1. Install nodejs. Use the displayed version number to check whether node. JS is installed.
node --version
2. Create a project directory (folder) and install the module.
npm install expressnpm install body-parser
Express is a Node. js Web application framework: http://expressjs.com/
BodyParser is used to parse the http Request body: https://github.com/expressjs/body-parser
3. Create a createServer. js
Var express = require ('express '); var bodyParser = require ('body-parser'); var fs = require ('fs'); var app = express (); // bodyParser. urlencoded parses the data app submitted by form. use (bodyParser. urlencoded ({extended: false}); // bodyParser. json parses the app in json data format. use (bodyParser. json (); app. post ('/saveJSON', function (req, res) {// convert an object to a string var str_json = JSON. stringify (req. body); fs. writeFile ('graph. json ', str_json, 'utf8', function () {// The console of the callback function after saving. log ("saved") ;};}); app. listen (0, 3000 );
4. Run createServer. js.
Node createServer.js
It monitors requests sent from http: // 127.0.0.1: 3000.
If the request comes from: http: // 127.0.0.1: 3000/saveJSON, it will save a graph. json file in the Server Directory, which contains post data sent by the client.
Front end
// Create an object var person = {name: "lucy", age: 25} // send a POST request with JQuery, whose content is person $. post ("http: // 127.0.0.1: 3000/saveJSON", person, function (data, status) {alert ("Data:" + data + "\ nStatus: "+ status );});
After loading in the browser, the backend console displays "Save complete", which is the callback function we wrote in writeFile. A graph. json file is added to the server directory to verify that the result is correct.
Summary
The above is all about this article. I hope this article will help you in your study or work. If you have any questions, please leave a message. Thank you for your support.