Node.js入门教程 第五篇 (Express框架)

Express框架


Express是适用于Node.js web的框架,提供了大量实用功能,例如路由功能及http功能。

Express 框架核心特性:

  • 可以设置中间件来响应 HTTP 请求。
  • 定义了路由表用于执行不同的 HTTP 请求动作。
  • 可以通过向模板传递参数来动态渲染 HTML 页面。

 

安装:

 npm install express --save 

 

可能需要的中间件:

body-parser - Node.js 中间件,用于处理 JSON, Raw, Text 和 URL 编码的数据。

cookie-parser - 这就是一个解析Cookie的工具。通过req.cookies可以取到传过来的cookie,并把它们转成对象。

multer - Node.js 中间件,用于处理 enctype="multipart/form-data"(设置表单的MIME编码)的表单数据。

cors - Node.js跨域解决方案,当需要跨域访问时使用。

 npm install body-parser --save
 npm install cookie-parser --save
 npm install multer --save
 npm install cors --save

使用express创建服务端:

 var express = require('express');
 var app = express();
  //分配路由
 app.get('/', function (req, res) {
    res.send('Hello World');
 })
 app.get('/about', function (req, res) {
    res.send('about web');
 })
 app.post('/user', function (req, res) {
    res.send('user data');
 })
 //创建服务器并监听8080端口
 var server = app.listen(8080)

访问 http://127.0.0.1:8080:

界面输出'Hello World'

访问 http://127.0.0.1:8080/about:

界面输出'about web'

访问 http://127.0.0.1:8080/user:

界面输出'user data'

 Express的路由分为get和post两种。两者用法类似,但post支持的参数长度更大。

 

express+axios实现vue前后端跨域访问(拓展)


axios是对ajax封装后的模块,使用更简单,可以与express搭配使用,实现前后端分离跨域访问。

安装axios:

 npm install axios --save 

 使用express创建路由:

 //router.js
 const express = require('express');
 const router = express.Router();
 
 router.get('/login', (req, res, next) => {
   //to do login
 });

创建跨域访问:

 const routerApi = require('./router');
 const bodyParser = require('body-parser'); // post 数据需要
 const express = require('express');
 const cors = require('cors');//跨域访问依赖的中间件
 const app = express();
 
 // 允许请求的域名,如果是*则允许所有域名访问本服务端(必须写在所有注册路由前)
 app.use(cors({ origin: 'http://127.0.0.1:8080' }));
 //解析Json
 app.use(bodyParser.json());
 //注册路由
 app.use('/api', routerApi);
 //创建服务端,监听端口
 app.listen(3000, '0.0.0.0');
 console.log('success listen at port:3000......');

前端main.js(前端以Vue为例):

 import Vue from 'vue'
 import axios from 'axios'
 
 //使用ElementUI为PC前端框架
 Vue.use(ElementUI)
 // 请求服务器的Url
 axios.defaults.baseURL = 'http://127.0.0.1:3000/';
 //设置post默认类型为json
 axios.defaults.headers.post['Content-Type'] = 'application/json';
 Vue.prototype.axios = axios

前端UI请求:

 this.axios.get("/api/login", {
    params: {
      userName: 'Jimmy',
      password: '123456'
    }
  })
  .then(res => {
   //登录结果...
  })
  .catch(error => {
    console.log(error.response);
  });

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值