node、express(路由)簡單搭建伺服器
阿新 • • 發佈:2020-12-19
1.node
原始: var http = require( 'http' ) var server = http.createServer() server.on( 'request', function(req res){ var url = req.url if(url = '/'){ res.setHeader( 'content-Type', 'text/plain; charset = utf-8' ) //根據型別設定,html裡自帶有,fs裡第二個引數可直接加 'utf8' res.end('請求成功了') } }) server.listen(3000, function ( ) { '伺服器啟動成功' }) 簡化: vat http = require( 'http' ) http .createServer(req, res){ var url = req.url if(url = '/'){ res.end('ok') } } .listen(3000, function ( ) { '伺服器啟動成功' })
2.express
var express = require( 'express' ) var app = express.server () app.get( '/', function(req, res){ res.send( '請求成功了' ) ) app.listen(300, function(){console.log('伺服器啟動成功')}) // 路由 var express = require ( 'express' ) var router = express.Router () router.get( '/' , function(req, res){ res.render( 'index.html', {stus: syus}) //要先下載 art-template express-art-template 包用以渲染頁面 })
module.exports = router