NodeJS Express应用

1)初步介绍

模块的介绍

  • express 主要模块
  • body-parser 处理json,raw,url编码的数据
  • cookie-parser cookie的使用模块
  • multer 处理enctype="multipart/form-data"的表单数据 言外之意处理有上传功能的表单

2)初步应用

var express = require('express');
var app = express();
//分配路由
app.get('/',function(req,res){
  res.writeHead(200,{'Content-Type':'text/plain'});
  res.write('Hello Express');
  res.end()
})
app.get('/list',function(req,res){
  res.writeHead(200,{'Content-Type':'text/html;charset=utf8'});
  res.write('这是列表页');
  res.end()
})
//监听端口
app.listen(5000,function(){
  console.log('应用成功!');
})

分别访问localhsot:5000和localhsot:5000/list

3)渲染本地html网页发布上web服务器上

先在本地创建index.html网页其中先不需要外链资源文件例如link

var express= require('express'),fs = require('fs');
var app = express();
app.get('/',function(req,res){
  fs.readFile(path,function(err,chunk){
    if(err){
      console.log('请求出错)
    }else{
      res.writeHead(200,{'Content-Type':'text/html;charset=utf8'});
      res.write(chunk.toString())   //=>Buffer对象转换
      res.end();
    }
  })
})
app.listen(5000,function(){
  console.log('应用成功!');
})

直接访问localhost:5000即可访问到写的index.html网页

4)解决上面的外链资源文件 static

app.use(express.static(path)) 注意此处有坑!!!

var express= require('express');
var app = express();
app.use(express.static('img'))  //设置静态资源文件
app.get('/',function(req,res){
      res.writeHead(200,{'Content-Type':'text/html;charset=utf8'});
      res.write('金泰资源文件')   //=>Buffer对象转换
      res.end();
})
app.listen(5000,function(){
  console.log('应用成功!');
})

访问localhost:5000/logo.jpg可以正常访问到图片
而当我们使用刚刚的use里面的路径localhost:5000/img/logo.jpg就找不到该文件!
知道这个之后 在index.html里面链接的时候就可以注意点




    
    Title
    
    


    
你好啊
NodeJS Express应用_第1张图片
image.png

创建server.js

/*express 设置静态文件的请求!!!例如网站的css文件啊 一些img文件夹下的图片啊*/
var express = require('express'),fs = require('fs');
var app = express();
app.use(express.static('./css')); //此时设置的静态资源路径是css

app.get('/',function (req,res) {
    fs.readFile('./index.html',function (err,chunk) {
        if(err){
            res.writeHead(404,{'Content-Type':'text/html;charset=utf8'});
            res.write('404页面找不到了!')
            res.end();

        }else{
            res.writeHead(200,{'Content-Type':'text/html;charset=utf8'});
            res.write(chunk.toString())
            res.end()
        }
    })
})
app.listen(5000,function () {
    console.log('express设置静态文件资源')
})

访问http://localhost:5000/即可

你可能感兴趣的:(NodeJS Express应用)