nodejs创建简单服务器
Posted 一夜梦想
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了nodejs创建简单服务器相关的知识,希望对你有一定的参考价值。
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创建简单服务器的主要内容,如果未能解决你的问题,请参考以下文章