Git Product home page Git Product logo

talk's People

Contributors

ices1 avatar

Stargazers

 avatar

talk's Issues

Vue 上传表单 (含文件) 到服务器

Vue 上传表单 (文件) 到服务器

前端

  • 方法一,常规上传
    
    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) {
          /*这里做处理*/
        }
      })
    },
  • 方法二,上传basse64位格式
    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

axios 前后端请求(cookies )

Vue-BBS

前端 Post 报错 Access-Control-Allow-Header

  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()
  })

前端使用 axios post,后端接受数据为空

原因: 默认表单上传格式 为 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)
    })

axios 跨域处理以及带 cookies 的请求

日常开发中,有些接口可能需要前端请求的时候携带 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)

Vue 相同路由自刷新(参数)

Vue 相同路由参数不同不会刷新的问题

    // include 仅缓存 Home 页面下的

      <keep-alive include="Home">
      // :key 给 router-view 设置 key 属性为路由的完整路径
        <router-view :key="$route.fullPath" :isLogin='isLogin' @loginStatus='showLogin' />
      </keep-alive>

router
参考

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.