在中发送修改的用户信息,在得到res后,向data中赋值改变,
会报错说data中的东西未定义!第一次碰到这种情况,也不知道怎么解决。
vue中159行开始
<template>
<div >
<!-- 头部标题栏 -->
<HeadTop title="个人信息中心">
<span slot="left">
<div @click="routerback">
<Icon type="md-arrow-round-back" size="20" /><span>返回</span>
</div>
</span>
<span slot="right"></span>
</HeadTop>
<!-- 内容 -->
<div>
<div class="upload">
<!-- 个人信息 -->
<div style="width:280px;margin:0 auto;text-align:center;">
<!-- 展示用户信息,可以修改 -->
<div v-if="showInfo">
<Form :model="info" label-position="right" :label-width="100">
<img :src="" width="60" height="60"/>
<FormItem label="昵称:" style="text-align:left;">
{{}}
</FormItem>
<FormItem label="简介:" style="text-align:left;">
{{}}
</FormItem>
</Form>
<Button type="warning" @click="changeInfo" ghost>修改</Button>
</div>
<!-- 修改用户信息表单 -->
<div v-if="showForm">
<Form :model="info" label-position="left" :label-width="100">
<div>
<img @="uploadHeadImg" :src="" width="60" height="60"/>
<input type="file" accept="image/*" @change="handleFile" />
</div>
<FormItem label="昵称">
<Input v-model="" />
</FormItem>
<FormItem label="简介">
<Input type="textarea" v-model="" :autosize="{minRows: 2,maxRows: 5}" />
</FormItem>
</Form>
<Button type="success" @click="sureInfo" ghost>确定</Button>
<Button type="info" @click="cancelInfo" ghost>取消</Button>
</div>
{{}}
{{}}
</div>
<!-- 上传图片 -->
<div v-if="true">
<!--图片上传-->
<div class="weui-gallery" >
<span class="weui-gallery__img" ></span>
<div class="weui-gallery__opr">
<a href="javascript:" class="weui-gallery__del">
<i class="weui-icon-delete weui-icon_gallery-delete"></i>
</a>
</div>
</div>
<div class="weui-cells weui-cells_form">
<div class="weui-cell">
<div class="weui-cell__bd">
<textarea class="weui-textarea" v-model="content" placeholder="你想说啥" rows="3"></textarea>
</div>
</div>
<div class="weui-cell">
<div class="weui-cell__bd">
<div class="weui-uploader">
<div class="weui-uploader__bd">
<ul class="weui-uploader__files" >
<li ref="files" class="weui-uploader__file" v-for="(image,index) in images" :key="index"
:style="'backgroundImage:url(' + image +' )'"><span @click="deleteimg(index)" class="x">×</span></li>
</ul>
<div v-show=" < maxCount" class="weui-uploader__input-box">
<input @change="change" class="weui-uploader__input " type="file"
multiple accept="image/*">
</div>
</div>
</div>
</div>
</div>
</div>
<a class="weui-btn weui-btn_primary btn-put" style="margin: 20px " @="put">发送</a>
</div>
</div>
</div>
</div>
</template>
<script>
import store from '../../vuex/store'
import HeadTop from '../components/HeadTop/HeadTop'
import axios from 'axios'
export default {
name:"Infocenter",
data(){
return {
//用户框,修改框 展示与否
showInfo:true,
showForm:false,
//用户信息(来接受路由传递过来的query),并且在界面上动态改变,如果用户确定则向后台提交
info:{},
//缓存用户信息,防止取消修改信息后原信息丢失
oldinfo:{},
//待上传的图片文件
pic_file:{},
//上传头像相关
content: '',//分享动态的文字内容
maxSize: 10240000 / 2,//图片的最大大小
maxCount: 8,//最大数量
filesArr: [],//保存要上传图片的数组
images: []//转成base64后的图片的数组
}
},
//引入vuex
store,
//引入子组件
components: {
HeadTop,
},
//方法
methods:{
//后退:返回上一个页面
routerback(){
this.$(-1);
},
changeInfo(){
// 用户信息框消失,修改信息框展示
= false;
= true;
},
sureInfo(){//确定修改用户信息,并提交给后台
// 用户信息框展示,修改信息框消息
= true;
= false;
//添加接口所需的数据file--头像,username--用户名,disc--简介,_id--唯一标识
var formData=new FormData();// 创建form对象:接口所需的所有数据formData
('file',this.pic_file);
('username', );
('disc', );
('_id', ._id);
('打印formData')
(formData)
('http://localhost:4444/shangchuan', formData, {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}).then(function (res) {
alert('修改个人信息成功!!!');
(res)
()
()
= ;
();
this.$({path: '/me'});
})
.catch(err=>{
alert('修改个人信息失败!');
(err);
})
},
cancelInfo(){ //取消 修改用户信息
// 用户信息框展示,修改信息框消息
= true;
= false;
//缓存用户信息,防止取消修改信息后原信息丢失
= ({}, );
},
//头像上传
// 打开图片上传
uploadHeadImg: function () {
this.$('#hiddenInput').click();
},
//点击图片触发 将头像显示(不涉及上传图片)
handleFile: function (e) {
let $target = || ;//找到input节点
let file = $[0];//找到上传的图片
this.pic_file = $[0];//存入data中
//初始化
= new FormData();
// 单纯将头像显示
var reader = new FileReader();//将文件内容读入内存,访问本地文件
= (data) => {//当读取操作成功完成时调用
let res = || ;//捕获当前事件作用的对象
= ;//图片被转换成了二进制流(字符串类型),存储在info的avatarurl中
};
(file);//将图片内嵌在网页之中--Base64
},
// 上传头像相关的所有方法--开始
//删除图片
deleteimg(index) {
(index, 1);
(index, 1);
},
//改变图片
change(e) {
let files = ;
// 如果没有选中文件,直接返回
if ( === 0) {
return;
}
if ( + > ) {
Toast('最多只能上传' + + '张图片!');
return;
}
let reader;
let file;
let images = ;
for (let i = 0; i < ; i++) {
file = files[i];
(file);
reader = new FileReader();
if ( > ) {
Toast('图片太大,不允许上传!');
continue;
}
= (e) => {
let img = new Image();
= function () {
let canvas = ('canvas');
let ctx = ('2d');
let w = ;
let h = ;
// 设置 canvas 的宽度和高度
= w;
= h;
(img, 0, 0, w, h);
let base64 = ('image/png');
(base64);
};
= ;
};
(file);
}
},
//发送方法
put() {
let self = this;
let content = ;
let param = new FormData();
('content', content);
('username', 'wofsfsdf');
((file) => {
('file2', file);
});
('http://localhost:4444/uploadFile', param, {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}).then(function (result) {
();
this.$({path: '/world'});
Toast()
})
},// 上传头像相关的所有方法--结束
},//methods-end
//beforeCreate 将路由中的 用户信息 赋值到 data(){} 中
beforeCreate(){
//防止token已经过期
var localtoken = ("token");
var localusername = ("user_name");
var localparams = {
token:localtoken,
user_name:localusername
};
this.$axios({
url:"http://localhost:4444/users/islogin",
method:"get",
params:localparams
})
.then(res=>{
('这里是vue初始化生命周期:');
if( == 200){
= ;
//对象赋值,分配一块新的内存空间
= ({}, );
();
}
})
.catch(err=>{
(err)
})
},//beforreCreate-end
}
</script>
<style scoped>
#hiddenInput{
display: none;
}
</style>
var express = require('express');
var router = ();
var path = require("path");
var User = require("../models/User");
var Info = require("../models/Info");
//图片上传模块
var multer = require('multer');
let OSS = require('ali-oss');
//阿里云oss配置自己去官网瞧
let client = new OSS({
region: 'oss-cn-shanghai',
accessKeyId: '****',
accessKeySecret: '******'
});
('******');
/* GET home page. */
('/', function(req, res, next) {
('index', { title: 'Express' });
});
async function put(fileName, filePath, cb) {
try {
let result = await (fileName, filePath);
("public/images/uploads/" + );
cb(result)
} catch (err) {
(err);
}
}
let filePath;
let fileName;
let Storage = ({
destination: function (req, file, cb) {//计算图片存放地址
cb(null, './public/images/uploads');
},
filename: function (req, file, cb) {//图片文件名
fileName = () + '_' + parseInt(() * 1000000) + '.png';
filePath = '/public/images/uploads/' + fileName;
cb(null, fileName)
}
});
let upload = multer({ storage: Storage }).any();//file2表示图片上传文件的key
//自己写的用户信息接收
('/shangchuan', function (req, res, next) {
upload(req, res, function (err) {
let content = || "";
let username = ;
let imgs = []; //要保存到数据库的图片地址数组
if (err) {
return (err);
}
('进入图片解析--------')
()
('打印 ------')
()
// ("打印 [0].path------");
// ([0].path);
// (content)
// (content)
// (username)
((item, index) => {
var filePath = `http://localhost:4444/public/images/uploads/${}`;
('数据库中的路径filePath------------')
(filePath)
});
({
avatarurl: filePath,
mag: "修改个人信息成功"
});
});
});
//网络查的 接收用户信息
('/uploadFile', function (req, res, next) {
upload(req, res, function (err) {
let content = || '';
let username = ;
let imgs = [];//要保存到数据库的图片地址数组
if (err) {
return (err);
}
if ( === 0) {
new Pyq({
writer: username,
content: content
}).save().then((result) => {
({
result: result,
code: '0',
msg: '上传成功'
});
})
}
/*('public/img/', function (err) {
(err)
});*/
let i = 0;
((item, index) => {
let filePath = `./public/images/uploads/${}`;
put(, filePath, (result) => {
();
i++;
if (i === ) {
//forEach循环是同步的,但上传图片是异步的,所以用一个i去标记图片是否全部上传成功
//这时才把数据保存到数据库
new Pyq({
content: content,
writer: username,
pimg: imgs
}).save().then(() => {
({
code: '0',
msg: '发布成功'
});
})
}
})
})
})
});
= router;
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
//加载数据库模块
var mongoose = require("mongoose");
// 引入jwt token工具
const JwtUtil = require('./public/utils/jwt');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
//解决跨域
('*', function (req, res, next) {
//将外源设为指定的域,比如:http://localhost:8080
("Access-Control-Allow-Origin", "*");
//将Access-Control-Allow-Credentials设为true 允许携带cookie
('Access-Control-Allow-Credentials', true);
("Access-Control-Allow-Headers", "X-Requested-With");
("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
("X-Powered-By", ' 3.2.1');
//配置options的请求返回,解决axios的post自定义头部字段问题
// if (().equals("OPTIONS")) {
// (response, (), null);
// return;
// }
//返回数据格式为json字符串
("Content-Type", "application/json;charset=utf-8");
next();
});
// view engine setup
('views', (__dirname, 'views'));
('view engine', 'jade');
(logger('dev'));
(());
(({ extended: false }));
(cookieParser());
('/public', ('public'));//将文件设置成静态
// (((__dirname, 'public')));
/* 请求拦截器
*/
// (function (req, res, next) {
// var url = ;
// // 正则表达式匹配 匹配api '?' 前的路径,去除query参数
// url = (/(\S*)\?/)[1];
// // ('匹配正则后');
// // (url);
// // 把登陆和注册请求去掉了,其他的多有请求都需要进行token校验
// if (url != "/users/login" && url != "/users/register") {
// ("进入拦截器,打印result");
// /*没有弄明白怎么在headers中设置token
// let token = ;
// */
// let token = ;
// let jwt = new JwtUtil(token);
// let result = ();
// // 如果考验通过就next,否则就返回登陆信息不正确(与返回有关)
// if (result == 'err') {
// ('token已过期,被拦截器拦截');
// (result);
// ({ status: 403, msg: "尚未登录(登录已过期),请重新登录!" });
// } else {
// ('token没过期,进入对应的路由')
// next();
// }
// } else {
// //放过 登录 和 注册 请求
// next();
// }
// });
('/', indexRouter);
('/users', usersRouter);
// catch 404 and forward to error handler
(function(req, res, next) {
next(createError(404));
});
// error handler
(function(err, req, res, next) {
// set locals, only providing error in development
= ;
= ('env') === 'development' ? err : {};
// render the error page
( || 500);
('error');
});
//连接数据库
('mongodb://localhost:27222/blog', function (err) {
if (err) {
(err);
('数据库连接失败!');
} else {
("数据库连接成功!");
}
});
= app;