var http = require("http"); var dateModule = require('./currentDate');
// Read the port from the underlying environment. // If not exist, use the default port: 8080 var port = process.env.VCAP_APP_PORT || 8080;
// Create the server and listen to requests on the specified port. http.createServer(function (request, response) { // Set the content type of the response response.writeHead(200, {'Content-Type': 'text/plain'}); // Write a simple Hello World message, // Write a simple Hello World message appended with the current date response.end('Hello NodeJS! The time now is: ' + dateModule.currentDateTime()); }).listen(port);
根/vy102-qqq-nodejs/package.json
1 2 3 4 5 6 7 8
{ "name": "NodejsStarterApp", "version": "0.0.1", "description": "A Hello World NodeJS sample", "scripts": { "start": "node app.js" } }
var helloText = 'Hello'; var fromLanguage = 'en'; var toLanguage = 'es';
var portNumber = process.env.VCAP_APP_PORT || 8080; const server = http.createServer(handleRequests); server.listen(portNumber, function () { console.log('Server is up!'); });
var port = process.env.VCAP_APP_PORT || 8080; //Express Web Framework, and create a new express server var express = require('express'), app = express(); var bodyParser = require('body-parser');
//Routes modules var index = require('./routes'), author = require('./routes/author');
//In case the caller access any URI under the root /, call index route app.use('/', index);
//In case the caller access any URI under /author, call author route app.use('/author', author);
// start server on the specified port and binding host app.listen(port);
views/index.html
1 2 3 4 5 6 7 8 9 10 11 12
<html>
<body> <h1style="color:blue;">Watson Author Finder</h1> <p>To get information about the author of an article, enter the URL of that article.</p> <formaction="author"method="post"> <inputtype="text"name="url" /> <inputtype="submit"value="Submit" /> </form> </body>
// Watson Natural Language Understanding third party module //Specify the release for the Natural Language Understanding service var NaturalLanguageUnderstandingV1 = require('watson-developer-cloud/natural-language-understanding/v1.js'); var natural_language_understanding = new NaturalLanguageUnderstandingV1({ 'version_date': NaturalLanguageUnderstandingV1.VERSION_DATE_2017_02_27, iam_apikey: 'hySqyRqhRmlCaUeMlxF8Sk29T8ovIGzkFYOfVZH33oPQ', url: 'https://gateway-syd.watsonplatform.net/natural-language-understanding/api' });
//error message for missing URL const MISSING_URL_ERROR = 'URL not passed';
exports.extractArticleAuthorNames = function (req, callback) {
//If the url is not passed, return error to the caller if (req === null || req.body === null || req.body.url === null) { callback(MISSING_URL_ERROR, null); return; }
// url is the parameter passed in the POST request to /author // It contains the URL of the article // The metadata feature returns the author, title, and publication date. var parameters = { 'url': req.body.url, 'features': { 'metadata': {} } };
// Call the Watson service and return the list of authors natural_language_understanding.analyze(parameters, function (err, response) { if (err) callback(err, null); else callback(null, response.metadata.authors); });
};
routes/index.js
1 2 3 4 5 6 7 8 9 10 11 12 13
// index.js - Index route module var express = require('express'); var router = express.Router();
//Provides utilities for dealing with directories var path = require('path');
// Home page route router.get('/', function (req, res) { res.sendFile(path.join(__dirname, '../views/index.html')); });
module.exports = router;
routes/author.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// author.js - Author route module var express = require('express'); var router = express.Router(); var articleServices = require('../services/articleServices');
router.post('/', function (req, res) { articleServices.extractArticleAuthorNames(req, function (err, response) { if (err) res.status(500).send('error: ' + err); else res.send(response); }); });
module.exports = router;
4. Building a rich front-end application by using React and ES6
// getAuthor uses the fetch function to retrieve authors // from the REST service created in the previous exercise getAuthor() { var myHeaders = new Headers(); myHeaders.append("Content-Type", "application/x-www-form-urlencoded"); fetch('/author', { method: 'POST', body: "url=" + this.state.inputVal, headers: myHeaders }).then(res => res.json()) .then(data =>this.setState({ authors: data, url: this.state.inputVal })); }
// Render is the core function behind React components. // It defines components and elements in XML format. // This is only feasible if using JSPX and Babel JavaScript compiler. render() { return ( <div class="jumbotron text-center"> <h1>Author Finder</h1> <div id='input-form' class='text-center'> <input type="text" class="form-control input-lg text-center" onChange={e=>this.updateUrl(e)} placeholder="Enter URL of Article here!"/> </div> <br/> <button type="button"class="btn btn-primary btn-lg" disabled = {this.state.inputVal.length===0} onClick={()=>{this.getAuthor()}}>Retrieve Author</button> <Results url={this.state.url} hide={this.state.authors.length === 0} authors={this.state.authors}/> </div> ) } } // Results: is another React component // It creates the list of AuthorRecords class Results extends React.Component { constructor(props) { super(props); } render() { if (this.props.hide) { return null; } return ( <div class='form-inline'> <div class="row"> <div class="col-xs-12 col-md-3"> <h2>Article URL:</h2> </div> <div class="col-xs-12 col-md-9"> {this.props.url} </div> </div> <div class="row"> <div class="col-xs-12 col-md-3"> <h2>Authors:</h2> </div> <div class="col-xs-12 col-md-9"> <div class="row"> {this.renderAuthors()} </div> </div> </div> </div> ) } /* Notice the AuthorRecord is defined in a separate file. This is a powerful feature of the React Component: Putting the AuthorRecord in a separate file and making it a reusable component. */ renderAuthors() { /* When developing a component, you should capitalize it. Hence, you should use "AuthorRecord" instead of"authorrecord"in order to identify it as a component to React. */ let authors = this.props.authors; return authors.map(a => { return <AuthorRecord author = {a}/>; }); }
<body> <!-- Loading the script in body is a recommendation to ensure faster loading, putting all scripts at the header will cause the page to wait till all scripts loaded Load React related files from internet --> <scriptcrossoriginsrc="https://unpkg.com/react@16/umd/react.production.min.js"></script> <scriptcrossoriginsrc="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<!-- Load babel JavaScript compiler from internet --> <scriptsrc="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
<divclass="container"> <divclass="row"> <!-- You do not need to write much html code, you will build the whole html on your JSPX code --> <divclass="col-sm-10 col-sm-offset-1 text-center"id="root"> </div> </div> </div> </body>
var port = process.env.VCAP_APP_PORT || 8080; //Express Web Framework, and create a new express server var express = require('express'), app = express(); var bodyParser = require('body-parser');
//Routes modules var author = require('./routes/author');
//Serve the files in /frontend as static files app.use(express.static(__dirname + '/frontend'));