nodejs建立簡單伺服器

來源:互聯網
上載者:User

標籤: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建立簡單伺服器

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.