新建一个 nodejs 项目.
Pre install:
- Nodejs
- npm -
Steps:
- mkdir nodejs-hw-pure
- cd nodejs-hw-pure
- new file: hellonode.js
//引入required模块
var http = require("http");
//创建服务器
http.createServer(function(request,response){
//发送头部
response.writeHead(200,{'Content-Type':'text/plain'});
//发送响应数据
response.end('hello Nodejs...\n');
}).listen(8888);
//终端打印以下信息
console.log('Server running at http://127.0.0.1:8888/');
4. Run:
$ node hellonode.js
5. Verify on Browser (Chrome):
http://127.0.0.1:8888/
Use Express
$ npm install express --save
$ npm install body-parser --save
$ npm install cookie-parser --save
$ npm install multer --save
new file: helloworld-express.js
var express = require("express");
var app = express();
app.get('/', function(req, res) {
res.send('Hello Node by Express...');
})
var server = app.listen(8081, function() {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s;%s", host, port)
})
Run:
$ node helloworld-express.js
Verify on Browser (Chrome):
http://127.0.0.1:8081/
来源:oschina
链接:https://my.oschina.net/joryqiao/blog/4463642