zoukankan      html  css  js  c++  java
  • vue-cli 3.0之跨域请求代理配置及axios路径配置

    vue-cli 3.0之跨域请求代理配置及axios路径配置

    问题:在前后端分离的跨域请求中,报跨域问题

    配置:

    vue.config.js:

    module.exports = {
      runtimeCompiler: true,
      publicPath: '/', // 设置打包文件相对路径
      devServer: {
        // open: process.platform === 'darwin',
        // host: 'localhost',
        port: 8071,
        // open: true, //配置自动启动浏览器 
        proxy: {
          '/api': {
            target: 'http://127.0.0.1:8100/', //对应自己的接口
            changeOrigin: true,
            ws: true,
            pathRewrite: {
              '^/api': ''
            }
          }
        }
       }, 
    }

    配置后需要重启服务。

    配置axios的baseUrl。

    main.js:

    axios.defaults.timeout = 5000 // 请求超时
    axios.defaults.baseURL = '/api/'  // api 即上面 vue.config.js 中配置的地址
    

    发送请求:

    axios.post('/postData/', {
        name: 'cedric', 
    }).then((res) => {
      console.log(res.data)
    })
    

      此时,虽然请求发送到了:http://localhost:8080/api/postData/,但是已经代理到了地址:http://127.0.0.1.8100/postData/.控制台显示请求的地址为:http://localhost:8080/api/postData/。

    生产环境:

    只需要将 main.js 中 axios 作如下修改:

    axios.defaults.timeout = 5000 // 请求超时
    axios.defaults.baseURL = 'http://api.demourl.com/'
    

    页面中axios的请求保持不变:

    axios.post('/postData/', {
        name: 'cedric', 
    }).then((res) => {
      console.log(res.data)
    })

    实际请求地址为:http://api.demourl.com/postData/

    转载自:https://www.cnblogs.com/cckui/p/10331432.html

  • 相关阅读:
    SQL Server 2005高可用性之镜像功能
    Linux的常见问题解答和管理技巧
    安装sharepoint server 2007步骤
    CISCO 中对OSI的解释
    CISCO 2600 密码恢复
    三层交换机与路由器的比较
    PHP的注释
    php的变量、常量和数据类型
    操作符与控制结构
    【1】淘宝sdk装修入门引言
  • 原文地址:https://www.cnblogs.com/s313139232/p/10598071.html
Copyright © 2011-2022 走看看