Webpact packaging react back-end node+express

Source: Internet
Author: User
Tags node server hasownproperty

Webpact packaging react back end node+express preface

React is officially recommended to develop react components with browserify or Webpack .

What is Webpack? is a module loader developed by the German developer Tobias Koppers. Instagram engineers thought the plan was great and seemed to have passed the author. In Webpack, all the resources are considered as modules, JS, CSS, pictures and so on. Webpack have the corresponding module loader, the following will be used to Jsx-loader to load the JS file with react syntax

Express is currently the most popular node. JS Web MVC Development Framework and is most popular with web developers. With its powerful features, developers can create single-page and multi-page, and mixed-mode WEB applications. This example implements the data Model module with the JSON array simulation, realizes the restful API under the express frame.

[1] back end

First, installation and Configuration Environment [window environment]

1. Open the command line, install the monitoring code changes can automatically restart the node server supervisor

NPM install-g Supervisor

In the development of the NODEJS program, debugging, no matter what part of the code you modify, you need to restart the service to take effect. This design of node. JS, while improving performance, is not conducive to development debugging because we always want to see the effect as soon as we change it, rather than terminating the process and restarting it every time. Supervisor can help you implement this feature by monitoring your code changes and automatically restarting node. js.

2, command line Global installation NODEJS MVC Framework Express.

Note If you run a problem, you can add a version number to the installation.

NPM Install-g Express

3. Create a project using Express

CD E:\nelson\test\express\    express-t ejs commentboxcd commentboxnpm intall

As above: The command line to locate their own directory E:\nelson\test\express\, and then enter Express-t Ejs Commentbox create the project, at this time, a Commentbox folder is automatically generated. The folder will have model, public, routes and views folders, as well as app.js and Package.json two files. Then command line CD Commentbox to navigate to the Commentbox folder, and then enter NPM install (this is required), at this time, the directory will be more than Node_modules folder, this is the Node module folder.

Ii. Writing code

1. Add model file E:\nelson\test\express\commentbox\model\comments.js

Exports.comments = [  {author: ' Xiaoming ', text: "Nothing is impossible, the word itself says ' I ' m possible '!"},  {aut  Hor: ' Xiao Qiang ', text: "may not realize it when it happens, but a kick in the teeth is the best thing You "},  {author: ' Creeps ', text:" Even the greatest was once a beginner.  Don't be a afraid to take that first step. "},  {author: ' Bin Laden ', text:" You're afraid to die, and you're afraid to live. What a-to exist. "}";

using the JSON array to simulate the background data, of course, you can directly to the database, write database connection with the model can be.

2. Modify the application entry file E:\nelson\test\express\commentbox\app.js

/** * Module dependencies. */var Express = require (' Express '); var routes = require ('./routes ');var comment = require ('./routes/comment ');var http = require (' http '); var path = require (' path '); var app = Express ();//All Environmentsapp.set (' Port ', PROCESS.ENV.P ORT | | App.set (' Views ', Path.join (__dirname, ' views ')); App.set (' View engine ', ' Jade ');//app.use (Express.favicon ()); App.use (Express.logger (' dev ')); App.use (Express.json ()); App.use (express.urlencoded ()); App.use ( Express.methodoverride ());App.use (Express.bodyparser ());App.use (App.router); App.use (Express.static (Path.join (__dirname, ' public '));//Development Onlyif (' development ' = = App.get (' env ')) {App.use (Express.errorhandler ());} App.get ('/', routes.index);App.get ('/comments ', comment.list); App.get ('/comments/:id ', comment.get); App.delete ('/comments/:id ', comment.delete); App.post ('/comments ', comment.add); App.put ('/comments/:id ', comment.update);Http.createserver (APP). Listen (App.get (' Port '), function () {console.log (' Express server listening on port ' + app.get (' Port '));

Red parts are added to their own, the definition of additions and deletions to change the API interface. Code written in compliance with COMMONJS specifications

3. Increase the routing/Controller configuration file E:\nelson\test\express\commentbox\routes\comment.js

/* * GET comments listing. */var comments = require ('..    /model/comments '). Comments;  Exports.list = function (req, res) {Res.json (comments);    }; Exports.get = function (req, res) {if (comments.length <= req.params.id | | req.params.id < 0) {Res.statuscode    = 404;  Return Res.send (' Error 404:no comment found ');  } var q = comments[req.params.id]; Res.json (q);      };    Exports.delete = function (req, res) {if (comments.length <= req.params.id) {res.statuscode = 404;  Return Res.send (' Error 404:no comment found ');  } comments.splice (Req.params.id, 1); Res.json (TRUE);      };   Exports.update = function (req, res) {res.setheader (' content-type ', ' application/json;charset=utf-8 ');        for (Var i=0;i<comments.length;i++) {if (Comments[i].author==req.body.author) {comments[i] = Req.body;        Res.send ({status: "Success", message: "Update comment Success"});            Console.log (comments);      }  } }; Exports.add = function (req, res) {if (!req.body.hasownproperty (' author ') | |    !req.body.hasownproperty (' text ')) {Res.statuscode = 400;  Return Res.send (' Error 400:post syntax incorrect. ');    } var newcomment = {author:req.body.author, text:req.body.text};  Comments.push (NewComment);   Res.json (TRUE); };

Here is a clearer definition of the deletion and modification of the request processing

4, command line input Supervisor App.js,ok, now open the browser input localhost:3000 you can run and test API interface, you can also use postman or curl to test, this example only use Get and add request.

Supervisor App.js

Browser opens http://localhost:3000/comments

The results are as follows:

[  {    "author": "Xiaoming",    "text": "Nothing is impossible, the word itself says ' I ' m possible '!"  },  {    " Author ":" "Xiao Qiang",    "text": "Realize it when it happens, but a kick in the teeth is the best thing in the W Orld for You "  },  {    " author ":" Creep ",    " text ":" Even the greatest was once a beginner. Don't be a afraid to take that first step. "  },  {    " author ":" Bin Laden ",    " text ":" You're afraid to die, and you ' Re afraid to live. What a-to exist. "  }"

Browser opens HTTP://LOCALHOST:3000/COMMENTS/1

The results are as follows:

{  "author": "Xiao Qiang",  "text": "Realize it when it happens, but a kick in the teeth is the best thing I n The World "}

Back end to this end!

[2] Front end

First, configure the front-end environment 1, add webpack configuration file E:\nelson\test\express\commentbox\webpack.config.js

Module.exports = {    entry: [      './public/assets/js/entry.js '    ],    output: {        path: __dirname + '/public /assets/',        publicpath: "/public/assets/",        filename: ' Bundle.js '    },    module: {        loaders: [          { Test:/\.js?$/, loaders: [' Jsx-loader?harmony '}        ]}    };

Webpack.config.js is the default configuration file for Webpack. If you change the file name to re-execute: Webpack--config webpack.config.js Such a command, if you do not change the name of the direct input Webpack will automatically package the file.

2, the command line installs various dependent modules.

NPM install-g Webpack (requires global installation if Wepack is not installed)
NPM Install--save-dev Jsx-loader
NPM Install--save-dev reactnpm install--save-dev react-domnpm install--save-dev markednpm install--save-dev jquery

Second, write the front-end JS code

1, write react Message Edition components: E:\nelson\test\express\commentbox\public\assets\js\commentbox.js

var React = require (' React '), var reactdom = require (' React-dom '), var marked = require (' marked '); var $ = require (' jquery '); var Comment = React.createclass ({rawmarkup:function () {var rawmarkup = marked (This.props.children.toString (), {Sani    Tize:true});  return {__html:rawmarkup};          }, Render:function () {return (<div classname= "comment" > 

This example code is just like the official code of react, only changed to the Commonjs style. Note: Webpack from the COMMONJS specification, it is very convenient to use, require the corresponding modules, such as $ = require (' jquery '), you can use jquery directly, of course, first NPM installed the module to use.

2, webpack entrance js file: E:\nelson\test\express\commentbox\public\assets\js\entry.js

var React = require (' React '); var reactdom = require (' react-dom '); var commentbox = require ('./commentbox '); Reactdom.render (    <commentbox url= "/comments" pollinterval={2000}/>,    document.getElementById (' Commentbox '));

can refer to the 1th configuration file inside the definition of the entry JS file, the name and path to be consistent.

3, add message version static HTML page: E:\nelson\test\express\commentbox\public\html\index.html

<! DOCTYPE html>

Bundle.js file is webpack packaged JS file, reference can directly see the effect.

4, command line input webpack package JS file

Webpack

At this point, the Bundle.js file is automatically generated under directory E:\nelson\test\express\commentbox\public\assets according to the configuration file

5, good, done; At this point in the browser page you just opened the modified URL address is: http://localhost:3000/html/index.html, the effect is as follows:

Test on the page to leave a message, test pass, OK

Front-end react code reference from the official tutorial, slightly changed

--react Tutorial https://facebook.github.io/react/docs/tutorial.html

Back-end RESTful API interface reference from

--node.js and express-creating A REST API Http://blog.modulus.io/nodejs-and-express-create-rest-api

--nodejs+express to implement restful Web applications http://blog.csdn.net/jthink_/article/details/9708087

Tags: node, express, supervisor, React, Webpact, Jsx-loader

Webpact packaging react back-end node+express

Related Article

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.