Highcharts+nodejs Building Data Visualization platform

Source: Internet
Author: User

A period of time completed a data visualization project, built by the background nodejs+highcharts framework. Let's share the process of the entire development process and the experience of using the Highcharts framework.

First, the data read

Because the database is using MySQL database, in Nodejs, you can use the MySQL module in Nodejs for MySQL database operation, through NPM installation.

1. Basic Database Configuration

For convenience, we'd better start with a basic configuration of the database connection, and the MySQL module needs the following configuration information:

var connection = Mysql.createconnection ({  host     : ' 127.0.0.1 ',  user     : ' root ',  password: ' Root ',  database: ' Your_database ',  port:3306});
Tips: When we develop locally, we can first copy the data from the online database to local, such as PHP myadmin, and then read the local data for development.

2. Database connection

We can set, when access to a URL, automatically establish a MySQL connection, the code is as follows:

Router.get ('/test ', function (req, res, next) {  var username = req.cookies.username;  if (typeof username = = = "undefined" | | username! = "[email protected]") {    res.redirect ('/');  } else{    if (connection.threadid) {      return;    } else{      connection.connect (function (err) {        if (err) {          console.error (' Error connecting: ' + err.stack);          return;        }        Console.log (' Connected as ID ' + Connection.threadid);}}  )
Pay attention to the validation of this face. Our project here is relatively simple and uses only cookies for authentication. When we want to establish a database connection, we must first authenticate, otherwise anyone can send a request to our database to connect, will cause serious security risks.

Connect to the MySQL database by calling the Connect method in MySQL. Note here that the database connection cannot be parallel, otherwise it will be an error. So for the sake of security, we first have to determine whether the database is currently connected, and here you can use Connection.threadid to determine whether it is defined or not, and to determine if it has already established a connection. If you have already established a connection, do not establish the connection again.
3. Execute the query statement

By calling the query () method, you can handle the statement queries, enter any correct MySQL query statement, or nest other variables, and then just stitch out a string. Examples are as follows:

Router.post ('/test ', function (req, res, next) {  var startdate = req.body.startDate;  var endDate = req.body.endDate;  Connection.query (' SELECT ' Date ', COUNT (DISTINCT ' idea_id ') as num,     sum (' view ') as view, sum (' click ') as click,     SUM (' cost ') as cost from ' Idea_report_all '     where ' date ' between ' + StartDate + ' "and" ' + endDate +     ' "GROUP by ' Date ' ORDER by ' date ' ASC ', function (err, rows, fields) {    if (err) throw err;    var rows = calculate (rows);    Res.send (json.stringify (rows));  })
Here we are stitching into a query statement based on the obtained start date and due date, querying the data we need, and finally calling in the callback function (rows parameter), an array.

Finally, the data back to the front desk, the front desk for data processing and visualization.


Second, the use of highcharts

Highcharts can be used in the official API to view the various methods, and there are online demonstrations, very convenient (recommended highcharts Chinese network). The most troublesome of these is the objects that make up the various parameters that are required to draw the configuration items for the chart. It is recommended to set up a constructor that constructs this object to construct the corresponding Highcharts configuration items according to the parameters passed in. Because there are too many parameters passed in, we construct them in the form of objects. More on the use of the Highcharts framework will be updated later in the blog, you can first look at the following example of the construction.

function greateoptions (ID, text, xaxistitle, date, YAxisTitle1, YAxisTitle2, K1,unit1, K2,unit2, series, color, tooltip)  {var data = new Object ();d Ata.chart = {renderto:id, marginleft:50, margintop:70};  Data.colors = Color;data.title = {text:text,align: "Left"}; Data.tooltip = {crosshairs:true, shared:true, usehtml:true, style: {padding:10}, Headerforma    T: ' <table><tr><td> ' + tooltip + ':</td><td>{point.key}</td></tr> ', Pointformat: ' <tr><td style= ' color: {series.color} ' >{series.name}: </td> ' + ' <td styl  E= "Text-align:left" ><b>{point.y}</b></td></tr> ', Footerformat: ' </table> '};  Data.nodata = {style: {fontweight: ' bold ', FontSize: ' 15px ', color: ' #303030 '}};  Data.lang = {noData: "Loading data for You ..."}; Data.credits = {Enabled:false};d Ata.xaxis = {tickposition: ' outside ', title: {TexT:xaxistitle | | '}, categories:date};d ata.yaxis = [{linewidth:1,title: {text:yaxistitle1 | | '},labels: {formatter:function () {return this.value/k1 + unit1;}}},{linewidth:1,opposite:true,title: {text: YAxisTitle2 | | '},labels: {formatter:function () {return this.value/k2 + Unit2;}}]; Data.series = Series;return data;}

Highcharts+nodejs Building Data Visualization platform

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.