axios

作者: 雨说前端 | 来源:发表于2019-05-23 15:15 被阅读0次

    安装

    npm i axios(不是项目依赖不加-D)

    promise (异步加载)

    
    请求端口和服务器端口号不同是存在跨域会抛出异常,可以用代理解决跨域,vue中在config中的index.js中的proxyTable: {}写代理
    
    这个代理是用来解决跨域问题的
    proxyTable: {
           // 添加代理配置的
          '/api': { //匹配的代理规则
            target: "http://localhost:3000", // 要请求的目标
            // pathRewrite路径重写规则
            pathRewrite: {"^/api" : "/"}//将api替换成要匹配的
            
            用8080端口去请求3000端口
            // http://localhost:8080/api
            // http://localhost:3000/user
          }
    }
    
    在全局main.js中去写发送请求
    // Vue 使用axios模块来完成ajax 操作
    // https://www.npmjs.com/package/axios
    
    // http://localhost:8080/api/user
    // http://localhost:3000/user
    
    axios.get('/api/user')
    .then(res => {//用于接收参数
      console.log(res)
    })
     .catch(err => {//用于抛出异常
       console.log(err)
    })
    
    
    axios.post('/api/users/test', { user:'张三' })
       .then(res => {
         console.log(res)
       })
       .catch()
    
    axios({
      method: 'post',
      url:'/api/users/test',
      data: {
        user:'张三'
      },
      params: {
        type: 'a'
      }, 
      headers: {'RR-RR': 'XMLHttpRequest'},
      responseType: 'stream'
    }).then(res=> {
      console.log(res)
    })
    .catch(err =>{
    
    })
    
    在服务器express中写路由规则
    var express = require('express');
    var router = express.Router();
    
    /* GET users listing. */
    router.get('/', function(req, res, next) {
      res.send('respond with a resource');
    });
    
    
    router.post('/test', (req, res)=>{
      console.log(req.headers)
      res.json(req.body)
    })
    
    router.get('/login', function(req, res, next){
      res.status = 200
      const { username, password  } = req.query
      const err = {
        code: 0,
        err: {}
      }
    
      const result = {
        code: 1,
        data: req.query
      }
      if (!username) {
        err.err['username'] = '用户名不能为空'
      }
    
      if (!password) {
        err.err['password'] = '密码不能为空'
      }
    
      if(Object.keys(err.err).length > 0) {
        res.json(err)
      } else {
        res.json(result)
      }
    })
    
    导出
    module.exports = router;
    

    相关文章

      网友评论

          本文标题:axios

          本文链接:https://www.haomeiwen.com/subject/epxbzqtx.html