1. Install node related package
install --save react react-dom superagent
2, install Gulp related package
Install --save gulp-browserify Gulp reactify gulp-connect
3, write Gulpfile.js build react file
varGulp = require (' Gulp ')), Browserify= Require (' gulp-browserify '), Reactify= Require (' reactify '), connect= Require (' Gulp-connect '); Gulp.task (' Build ',function() {GULP.SRC (' Index.js '). Pipe (Browserify ({transform: [' Reactify ']). Pipe (Gulp.dest (' Build.js ')) }) Gulp.task (' Connect ',function() {connect.server ({port:3000, Livereload:true})}) Gulp.task (' HTML ',function() {GULP.SRC (' *.html '). Pipe (Connect.reload ())}) Gulp.task (' JS ', [' Build '],function() {GULP.SRC (' *.js '). Pipe (Connect.reload ())}) Gulp.task (' Watch ',function() {Gulp.watch (' *.html ', [' HTML ']) Gulp.watch (' *.js ', [' JS '])}) Gulp.task (' Default ', [' Build ', ' watch ', ' Connect ']
4. Writing Request requests
1. Added constant file constants.js to store the user name password for BASIC authentication in request requests
module.exports={ uname:' 123 ', pwd:' 123 '}
2. Add Call API file Api.js
var request = require (' superagent '); var constants = require ('./constants.js '= { function(callback) { Request . Get (' Http://localhost:53691/api/value ') . Auth (constants.uname, constants.pwd) . End (function(err, res) { if(err) { alert (err); } Callback (Res.body);} ); }
5. New Index.js
varReact=require (' React '), Reactdom=require (' React-dom '), API=require ('./api.js '));varitemlist=React.createclass ({getinitialstate:function(){ return{users:[]}}, Componentwillmount:function(){ varUsers=api. Get (function(users) { This. SetState ({users:users})}.bind ( This)); }, Render:function(){ varusers= This. State. Users; if(Array.isarray (users) = =false)Throw NewError (' Users are not array ') varLists=users.map (function(item) {return<li Key={item.id}>{item.id}:{item. Name}</li> }) return ( <ul>{lists}</ul> ) }}); Reactdom.render (<itemlist/>,document.getelementbyid (' app ')
6. New index.html
<!DOCTYPE HTML><HTMLLang= "en"><Head> <MetaCharSet= "UTF-8"> <title>Document</title></Head><Body> <H1>superagent!</H1> <DivID= "App"></Div> <Scriptsrc= "Build.js/index.js"></Script></Body></HTML>
Webapi Source
Calling ASP. WebApi in React