vue : 数据交互 get+post+jsonp (es6 / body-parser / bootstrap)

vue-resource

  • 特点:
    • 体积小
      • 压缩后大约12KB
    • 支持主流浏览器
      +不支持IE9以下的浏览器
    • 支持promise
      • promise 为es6的异步计算
    • 支持拦截器
      • 拦截器可以在请求发送前和发送后做一些操作

服务器 express + ejs + body-parser

想要请求数据,必然少不了服务器

准备工作
  1. 准备需要的文件 bootstrap.css + vue.js + vue-resource.js
  2. 初始化文件,生成packge.json文件,记录线上和线下所需的插件等
  npm init --y
  1. 下载服需要的插件 : npm/ cnpm 等
  • node :自带的包管理器
  • install :下载
  • --save :在package.json中存储为线上需要的插件
  • --save-dev : 在package.json中存储为线下需要的插件
  • express :基于node.js 平台,快速、开放、极简的文本开发框架
  • ejs :通过数据和模板,可以生成HTML标记文本,可以同时运行在客户端和服务器端,0 学习成本
  • body-parser :配合post 通过req.body获取前端的请求数据
  • node .\app.js : 开启服务器,链接端口为listen设置的值
    • 注意 :只要更改app.js ,都需要重新开启服务器
 npm install --save-dev express ejs body-parser
  1. 创建一个服务器文件 app.js 和 index.html文件
// 创建 app.js 
touch app.js 
// 创建 index.html
touch index.html

最终的文件目录为


vue : 数据交互 get+post+jsonp (es6 / body-parser / bootstrap)_第1张图片
最终文件目录.png
  1. html 页面准备
//  html 页面就不赘述了......



    
    
    
    Document
    


    
1111
  1. app.js 准备
// 引入express
const express = require('express');
// 引入 body-parser 插件,
const bodyParser = require('body-parser');
// 调用express
const app = express();
// 设置HTML模本
app.engine('html',require('ejs').renderFile);
// 中间件 : 设置静态资源文件夹
app.use(express.static('./'));
// 中间件 : 设置bodyParser
app.use(bodyParser.json());
// 链接服务器端口
app.listen(3000);


// 路由  req:存储的为用户发送的请求数据,res:存储的为服务器响应给用户的数据
app.get('/',(req,res)=>{
    /*
    * end : 只能发送字符串
    * send : 发送字符串 和 对象
    * render : 渲染页面
    */
    res.render('index');
});

  1. node .\app.js 开启服务器,并在浏览器访问localhost:3000 ,页面正常显示出 1111,证明成功
准备工作到此结束,下面开始正式代码,直接上代码了
html 页面



    
    
    
    Document
    


    

{{gs}}

{{ps}}

{{ss}}

app.js 页面
// 引入express
const express = require('express');
// 引入 body-parser 插件,
const bodyParser = require('body-parser');
// 调用express
const app = express();
// 设置HTML模本
app.engine('html',require('ejs').renderFile);
// 中间件 : 设置静态资源文件夹
app.use(express.static('./'));
// 中间件 : 设置bodyParser
app.use(bodyParser.json());
// 链接服务器端口
app.listen(3001);


// 路由  req:存储的为用户发送的请求数据,res:存储的为服务器响应给用户的数据
app.get('/',(req,res)=>{
    /*
    * end : 只能发送字符串
    * send : 发送字符串 和 对象
    * render : 渲染页面
    */
    res.render('index');
});

// get : req.query 获取前端传入的请求数据
app.get('/get',(req,res)=>{
    // console.log(req.query);
    res.send('这是get请求的数据')
});

/*
* post 
* 想要通过req.body获取数据需要配合 body-parser 插件
*/
app.post('/post',(req,res)=>{
    // console.log(req.body);
    res.send('这是post请求的数据');
});

你可能感兴趣的:(vue : 数据交互 get+post+jsonp (es6 / body-parser / bootstrap))