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跨域解决方案,当需要跨域访问时使用。

1 npm install body-parser --save
2 npm install cookie-parser --save
3 npm install multer --save
4 npm install cors --save

使用express创建服务端:

 1 var express = require('express');
 2 var app = express();
 3  //分配路由
 4 app.get('/', function (req, res) {
 5    res.send('Hello World');
 6 })
 7 app.get('/about', function (req, res) {
 8    res.send('about web');
 9 })
10 app.post('/user', function (req, res) {
11    res.send('user data');
12 })
13 //创建服务器并监听8080端口
14 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的路由分为getpost两种。两者用法类似,但post支持的参数长度更大。

 

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

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

安装axios

 npm install axios --save 

 使用express创建路由:

1 //router.js
2 const express = require('express');
3 const router = express.Router();
4 
5 router.get('/login', (req, res, next) => {
6   //to do login
7 });

创建跨域访问:

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

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

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

前端UI请求:

 1 this.axios.get("/api/login", {
 2    params: {
 3      userName: 'Jimmy',
 4      password: '123456'
 5    }
 6  })
 7  .then(res => {
 8   //登录结果...
 9  })
10  .catch(error => {
11    console.log(error.response);
12  });

猜你喜欢

转载自www.cnblogs.com/JHelius/p/11645929.html