码迷,mamicode.com
首页 > Web开发 > 详细

nodejs创建简单服务器

时间:2017-08-05 11:05:26      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:route   html   color   ==   path   nod   static   pen   logs   

1、创建package.jaon

1 {
2   "name": "application-name",
3   "version": "0.0.1",
4   "dependencies":{
5     "express": "latest"
6   }
7 }

2、创建index.js

1 "use strict";
2 let router = require(‘express‘).Router();
3 
4 router.get(‘/‘, function (req, res, next) {
5     console.log(‘index page‘);
6     res.redirect(‘index.html‘);
7 });
8 
9 module.exports = router;

3、创建app.js

 1 /**
 2  * Created by lenovo on 2017/8/1.
 3  */
 4 "use strict";
 5 
 6 let express = require(‘express‘);
 7 let app = express();
 8 let path = require("path");
 9 
10 let routes = require(‘./index‘);
11 /**
12  * 解决跨域问题
13  */
14 app.use(‘*‘, function (req, res, next) {
15     res.header("Access-Control-Allow-Origin", "*");
16     res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
17     res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
18     res.header("X-Powered-By",‘ 3.2.1‘);
19     if(req.method=="OPTIONS") res.send(200);/*让options请求快速返回*/
20     else  next();
21 });
22 
23 app.use(‘/‘, routes);
24 
25 //app.use(‘/‘, express.static(path.resolve("../") + ‘/static‘));
26 
27 module.exports = app;

4、创建www.js

1 "use strict";
2 
3 let app = require(‘./app‘);
4 let port = 8888;
5 
6 app.listen(port, () => {
7     console.log("Listening port:" + port);
8 });

5、安装node模块

6、node www.js运行服务器

nodejs创建简单服务器

标签:route   html   color   ==   path   nod   static   pen   logs   

原文地址:http://www.cnblogs.com/caiyingyong/p/7289340.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!