ices1 / talk Goto Github PK
View Code? Open in Web Editor NEW一个简单的BBS系统前端部分, Vue 实现, 部署于 VPS
Home Page: https://talk.iceeweb.com
一个简单的BBS系统前端部分, Vue 实现, 部署于 VPS
Home Page: https://talk.iceeweb.com
getFile(event) {
this.file = event.target.files[0];
console.log(this.file);
},
submitForm(event) {
event.preventDefault();
let formData = new FormData();
formData.append('name', this.name);
formData.append('age', this.age);
formData.append('file', this.file);
let config = {
headers: {
'Content-Type': 'multipart/form-data'
}
}
axios.post('/api/register', formData, config)
.then((res) => {
if (res.status === 200) {
/*这里做处理*/
}
})
},
getFile2 (event) {
let file = event.target.files[0]
let reader = new FileReader()
let img = new Image()
// 读取图片
reader.readAsDataURL(file)
// 读取完毕后的操作
reader.onloadend = (e) => {
img.src = e.target.result
// 这里的e.target就是reader
// console.log(reader.result)
// reader.result就是图片的base64字符串
this.base64 = reader.result
}
},
submitForm() {
axios.post('api/upload', base64)
.then(res => {
// ...
})
}
//引入文件模块
const multer = require('multer')
const upload = multer({dest: path.join(__dirname, 'user-uploaded')})
// 暴露存放地址接口
app.use('/api/avatars', express.static('./user-uploaded'))
// 注册,写入
app.route('/api/register')
.get((req, res, next) => {
// ...
})
.post(upload.single('avatar'), async (req, res, next) => {
let isExistUser = await db.get(
'SELECT id FROM users WHERE username = ?', req.body.username )
if (isExistUser) {
res.jsonp({status: 403, data :{message: '这个名字已经被注册咯,换个试试吧 &_& '}})
} else {
// 设定默认头像
if (!req.file) {
req.file = await db.get('SELECT avatar FROM users WHERE username = ?', '牛魔王')
req.file.filename = req.file.avatar
}
// 写入 数据(头像req.file.filename )
await db.run(
'INSERT INTO users (username, password, timestamp, avatar, email) VALUES (?, ?, ?, ?, ?)',
req.body.username, req.body.password, Date.now(), req.file.filename, req.body.email)
res.send({message: '注册成功'})
}
})
// 调用
// localhost:3002/api/avatars/xxxx
Request header field Content-Type is not allowed by Access-Control-Allow-Header
解决:(设置后端)
app.all('*', (req, res, next) => {
//设置跨域访问
res.header("Access-Control-Allow-Origin", "*")
//设置请求头及类型
res.header("Access-Control-Allow-Headers", "X-Requested-With")
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS")
res.header("X-Powered-By",' 3.2.1')
res.header("Content-Type", "application/json;charset=utf-8")
next()
})
原因: 默认表单上传格式 为 FormData
,后端也失败FormData
, 而axios
默认发送格式为 application/json
解决:引入 qs
转换 格式后发送
import qs from 'qs';
// axios.post('/api/login', data)
axios.post('/api/login', qs.stringify(data))
.then(function (res) {
console.log(res)
})
.catch(function (error) {
console.log(error)
})
日常开发中,有些接口可能需要前端请求的时候携带 cookies 来做身份判断等操作,而 axios 请求默认是不带 cookies 的,这时需要前端与后端同时做一些调整
// 对所有 axios 请求做处理(该处理为全局)
axios.defaults.withCredentials = true;
// 对单独的 axios 请求做处理
let {data} = await axios.get('//localhost:3000', {
withCredentials: true
})
此时前端请求已经可以正常携带 cookies 了,而且可以正常发出请求甚至得到数据,而请求仍然抛出了一个 error,导致即使可以从 network 中看到数据,仍然没法进行进一步的使用
此时需要后端做一些调整,具体操作参照报错信息即可,根据当前 demo 的情况,后端可对响应头做如下调整
// res.header("Access-Control-Allow-Origin", "*")
// 此处设置 * 无效,需要设定具体请求源
res.header("Access-Control-Allow-Origin", "http://localhost:1234")
res.header("Access-Control-Allow-Credentials", true)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.