前端跨域与代理

1、vue脚手架跨域与代理

1.跨域问题


文件config/index.js

原始代码:css

dev: {
    env: require('./dev.env'),
    port: 8080,
    autoOpenBrowser: true,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {},
    enabling this option.
    cssSourceMap: false
  }

proxyTable修改以下:vue

proxyTable: {
      '/api':{  
      //请求的服务器域名
        target:''
      }
    },

参考资料node

2.远程访问问题

目的:写好的项目但愿在其余电脑上或手机上查看。
webpack

方法:git

  • 打开文件 config/index.js,在dev对象中添加一个属性host,值为本机的ip地址
  • 打开文件 build/dev-server.js,定义一个常量localhost = config.dev.host ,再将这个文件里面的http://localhost按照原来的格式所有替换成刚定义的常量localhost。
    这样在其余电脑或者手机上直接访问这个ip地址便可。
//eg:
//添加这一行代码
const localhost = config.dev.host
//修改uri的值
const uri = localhost + ':' + port

2、常规webpack跨域与代理

找到配置文件中的出口(output)和入口(entry)配置,在同级对象下添加一个属性:github

devServer:{
        host:'172.16.0.105',  //代理地址-本机ip地址
        port:80,  //端口号
        proxy:{
            '/api':{
                target:''   //跨域访问地址
            }
        }
    }

webpack的其余配置案例web

3、常规代理问题(不依赖webpack等打包工具)

  • 在命令行输入 npm init 生成 package.json 文件(已经安装nodejs)
  • 经过 npm 安装 http-server,再在"script"对象中配置;
"scripts": {
    "dev":"http-server"
  },
  • 运行 npm run dev。
  • 而后就能够经过本机ip地址访问了

4、常规跨域问题(不依赖webpack等打包工具)

(同第三节)npm

"scripts": {
    "dev": "http-server -a 172.16.0.105 -p 8000 -P http://172.16.0.100:8080"
  },

第一个地址是本机ip地址及端口号,第二个地址是接口地址。json

相关文章
相关标签/搜索