请求端代码:
1 import Config from '../config'; 2 import Axios from 'axios'; 3 import iView from 'iview'; 4 import Qs from 'qs'; 5 6 export const axios = Axios.create({ 7 headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, 8 timeout: Config.axiosTimeout, 9 transformRequest: [(data) => { 10 data = Qs.stringify(data); 11 return data; 12 }] 13 }); 14 15 //登录验证相关…… 16 export const tokenMgr = { 17 getToken(formLogin) { 18 axios.post(Config.loginUrl, formLogin) 19 .then((res) => { 20 console.log(res.data); 21 if (res.data.success == true) { 22 localStorage.username = res.data.username; 23 sessionStorage.token = res.data.token; 24 location.href = '/home'; 25 } else { 26 iView.Message.error({ 27 content: '用户名或密码错误', 28 duration: 3 29 }); 30 } 31 }).catch((err) => { 32 console.log(err); 33 }); 34 }, 35 }
后端处理代码:
利用js模拟后端api
1 let Qs = require('qs'); 2 let http = require('http'); 3 let url = require('url'); 4 let fs = require('fs'); 5 6 http.createServer((req,res)=>{ 7 res.setHeader('Access-Control-Allow-Origin', '*'); 8 res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type,Content-Length,Authorization,Accpt,X-Requested-With'); 9 res.setHeader('Access-Control-Allow-Methods','PUT,POST,GET,DELETE,OPTIONS'); 10 res.setHeader('X-Powered-By',' 3.2.1'); 11 if (req.method == 'OPTIONS') { 12 return res.end(); /*让options请求快速返回*/ 13 } 14 let { pathname,query} = url.parse(req.url,true); //true把query转化为对象 15 16 console.log('pathname======>'+pathname); 17 if(pathname === '/loginSer/getToken'){ 18 let str = ''; 19 //将数据拼装起来 20 req.on('data',chunk=>{ 21 str += chunk; 22 }); 23 req.on('end',()=> { 24 let user = Qs.parse(str); //前台用的是qs对象封装 后台就得用qs解析 25 let data = {}; 26 if(user.username === 'admin' && user.password === 'admin'){ 27 data.success = true; 28 data.username = user.username; 29 data.token = 'token串'; 30 }else{ 31 data.success = false; 32 data.username = user.username; 33 } 34 res.end(JSON.stringify(data)); 35 }); 36 return ; 37 } 38 if(pathname === '/loginSer/reflashToken'){ 39 return; 40 } 41 if(pathname === '/loginSer/checkToken'){ 42 console.log(query.token+"11"); 43 return; 44 } 45 res.end(JSON.stringify({})); //删除返回空对象 46 }).listen(3000); 47 console.log('Server runing at port: 3000');
ps: vue中 在webpack.dev.config.js 中配置请求地址,实现跨域请求,代码如下:
devServer: { host: '127.0.0.1', port: 9001, proxy: { '/api': { target: 'http://IP地址:3000/', secure: false, changeOrigin: true, pathRewrite: {'^/api' : '/'}, } } }