美文网首页
十:Express框架基本使用

十:Express框架基本使用

作者: 谢玉胜 | 来源:发表于2018-06-08 10:29 被阅读0次

express框架

  1. 安装 npm install express --save
  2. 开启服务
新建一个项目->npm init ->npm install express
    
    
 var express = require('express');
//创建服务对象,类似于http.createServer
var app = express();
//程序监听9999端口号
// app.listen(9999)
app.listen(9999,function(){
    //监听ok的回调函数
    console.log("SERVER RUN")
})
//路由分发,处理以及回应请求
app.get('/',function(req,res){
    res.end("<h1>Hello Express</h1>")
    //1.req
    //获得「请求主体」/ Cookies
    console.log(req.body)
    //获取请求路径
    console.log(req.path)

    //2.res 设置一些返回信息数据
    //res.render(view,[locals],callback):渲染一个view,同时向callback传递渲染后的字符串,如果在渲染过程中有错误发生next(err)将会被自动调用。callback将会被传入一个可能发生的错误以及渲染后的页面,这样就不会自动输出了。
})

其中

  1. Request参数对象表示 HTTP 请求信息,比如:req.baseUrl:获取路由当前安装的URL路径
    req.path:获取请求路径
  2. Response 对象 表示 HTTP 响应,即在接收到请求时向客户端发送的 HTTP 响应数据 比如:res.status():设置HTTP状态码

路由

不同路径请求不同的数据,当然还要区分是Get还是POST请求(通过路由提取出请求的URL以及GET/POST参数。)

//  主页输出 "Hello World"
app.get('/', function (req, res) {
   console.log("主页 GET 请求");
   res.send('Hello GET');
})
 
 
//  POST 请求
app.post('/', function (req, res) {
   console.log("主页 POST 请求");
   res.send('Hello POST');
})
//  /list_user 页面 GET 请求
app.get('/list_user', function (req, res) {
   console.log("/list_user GET 请求");
   res.send('用户列表页面');
})
 
// 对页面 abcd, abxcd, ab123cd, 等响应 GET 请求
app.get('/ab*cd', function(req, res) {   
   console.log("/ab*cd GET 请求");
   res.send('正则匹配');
})

静态文件

图片/css/动画js等,express中存在static中间件来设置静态文件的路径,
比如

app.use(express.static('public'))
目录结构
 ---index.js
 ---public
    ---image
      ---logo.jpg

在public文件夹中有images文件夹,在images文件夹中有logo.jpg, 那么就可以在路径localhost:8888/images/logo.jpg中得到这张图片

表单的两种提交方式:POST vs GET

主要区别是get会通过&符号提交数据

  localhost:8888?name=xie&age=19
  1. GET:
<html>
<body>
<form action="http://127.0.0.1:8081/process_get" method="GET">
First Name: <input type="text" name="first_name">  <br>
Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</form>
</body>
</html>
var express = require('express');
var app = express();
 
app.use(express.static('public'));
 
app.get('/index.htm', function (req, res) {
   res.sendFile( __dirname + "/" + "index.htm" );
})
 
app.get('/process_get', function (req, res) {
 
   // 输出 JSON 格式
   var response = {
       "first_name":req.query.first_name,
       "last_name":req.query.last_name
   };
   console.log(response);
   res.end(JSON.stringify(response));
})
 
var server = app.listen(8081, function () {
 
  var host = server.address().address
  var port = server.address().port
 
  console.log("应用实例,访问地址为 http://%s:%s", host, port)
 
})

2.POST

<html>
<body>
<form action="http://127.0.0.1:8081/process_post" method="POST">
First Name: <input type="text" name="first_name">  <br>
 
Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</form>
</body>
</html>
var express = require('express');
var app = express();
//传递来的body里面的数据解析
var bodyParser = require('body-parser');
 
// 创建 application/x-www-form-urlencoded 编码解析
var urlencodedParser = bodyParser.urlencoded({ extended: false })
 
app.use(express.static('public'));
 
app.get('/index.htm', function (req, res) {
   res.sendFile( __dirname + "/" + "index.htm" );
})
 
app.post('/process_post', urlencodedParser, function (req, res) {
 
   // 输出 JSON 格式
   var response = {
       "first_name":req.body.first_name,
       "last_name":req.body.last_name
   };
   console.log(response);
   res.end(JSON.stringify(response));
})
 
var server = app.listen(8081, function () {
 
  var host = server.address().address
  var port = server.address().port
 
  console.log("应用实例,访问地址为 http://%s:%s", host, port)
 
})

文件上传

<html>
<head>
<title>文件上传表单</title>
</head>
<body>
<h3>文件上传:</h3>
选择一个文件上传: <br />
<form action="/file_upload" method="post" enctype="multipart/form-data">
<input type="file" name="image" size="50" />
<br />
<input type="submit" value="上传文件" />
</form>
</body>
</html>
var express = require('express');
var app = express();
var fs = require("fs");
 
var bodyParser = require('body-parser');
var multer  = require('multer');
 
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({ dest: '/tmp/'}).array('image'));
 
app.get('/index.htm', function (req, res) {
   res.sendFile( __dirname + "/" + "index.htm" );
})
 
app.post('/file_upload', function (req, res) {
 
   console.log(req.files[0]);  // 上传的文件信息
 
   var des_file = __dirname + "/" + req.files[0].originalname;
   fs.readFile( req.files[0].path, function (err, data) {
        fs.writeFile(des_file, data, function (err) {
         if( err ){
              console.log( err );
         }else{
               response = {
                   message:'File uploaded successfully', 
                   filename:req.files[0].originalname
              };
          }
          console.log( response );
          res.end( JSON.stringify( response ) );
       });
   });
})
 
var server = app.listen(8081, function () {
 
  var host = server.address().address
  var port = server.address().port
 
  console.log("应用实例,访问地址为 http://%s:%s", host, port)
 
})

RESTful API

rest以及RESTful API的理解
rest是一组架构约束条件和原则,符合REST设计标准的API,即RESTful API。,REST 通常使用 JSON 数据格式 所以RESTful Api就是通过JSON格式的数据返回的API,通俗而言就是前后端分离

相关文章

网友评论

      本文标题:十:Express框架基本使用

      本文链接:https://www.haomeiwen.com/subject/jjvosftx.html