Vue 跨域问题解决
【记】 Vue 跨域问题解决经过跨域问题发生在生产环境 和 开发环境开发环境 在config/index.js添加proxyTable代理接口在开发的时候,需要请求同局域网内的接口,发现直接使用http://对方的ip地址/接口路径,会出现类似下图的跨域报错解决方法:打开config/index.js,在dev中找到proxyTabledev: {// Paths...
·
Vue 跨域问题解决
Vue3.0版本
刚升级到
3.0版本
没有2.x版本
的webpack
目录,查看文档之后发现原来已经移除了,
要配置接口的代理得新建一个叫vue.config.js
的配置文件
如下代码片段
module.exports = {
devServer: { // 开发环境下runtime
proxy: { // 代理服务器
// 接口地址为 http://127.0.0.1:7001/api/register
'/api/register': {
target: 'http://127.0.0.1:7001',
secure: false, //是否使用 Https安全传输协议
changeOrigin: true
}
}
}
}
Vue2.x 版本
跨域问题发生在
生产环境
和开发环境
开发环境 使用proxyTable
将接口代理到本地
在开发的时候,需要请求同局域网内的接口,发现直接使用
http://对方的ip地址/接口路径
,会出现类似下图的跨域报错
打开
config/index.js
,在dev
中找到proxyTable
module.exports = { dev: { // Paths assetsSubDirectory: 'static', assetsPublicPath: '/', // 找到下面这个proxyTable 修改============================================== proxyTable: { // 下面是接口的路径,我的接口 地址是192.168.0.115:8088/login '/login': { // 需要转发代理的域名 target: 'http://192.168.0.115:8088', // 如果是https接口,需要配置这个参数 secure: false, // 如果接口跨域,需要进行这个参数配置 changeOrigin: true, // 这是一个通配符,设置完了之后每个接口都要在前面加上/api(特别注意这一点) // pathRewrite: { // '^/api': '' // } } }, // 找到上面面这个proxyTable 修改============================================== host: 'localhost', port: 8080, autoOpenBrowser: false, errorOverlay: true, notifyOnErrors: true, poll: false, showEslintErrorsInOverlay: false, devtool: 'cheap-module-eval-source-map', cacheBusting: true, cssSourceMap: true }
config/index.js
具体代码如下
调用方法:
App.vue
中使用
注意修改完config/index.js
配置文件需要重启一下,npm run dev
效果如下
至此,开发环境接口调试的跨域问题暂时算解决?
生产环境 利用Nginx做反向代理
在使用
yarn build
打包项目之后,打开页面发送请求发现报错了。也对,因为接口本来就不在我机器上
灾难现场
借助nginx进行反向代理,将接口代理到本地,先安装好 nginx安装教程
打开nginx.conf
, 找到server
,并在里面追加server { listen 80; server_name localhost; root "E:/Program Files/PHPTutorial/WWW"; location / { index index.html index.htm index.php l.php; autoindex off; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } location ~ \.php(.*)$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_split_path_info ^((?U).+\.php)(/?.+)$; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info; include fastcgi_params; } #这里是追加的===================================================== location /login { proxy_set_header Host $host; proxy_set_header x-forwarded-for $remote_addr; proxy_set_header X-Real-IP $remote_addr; proxy_pass http://192.168.0.115:8088/login; #填写接口地址 } #这里是追加的===================================================== }
重启Nginx
,刷新页面
参考:
更多推荐
已为社区贡献1条内容
所有评论(0)