当前位置: 首页 > 后端技术 > Node.js

使用gulp配置proxy简单解决前端跨域问题

时间:2023-04-03 23:10:59 Node.js

gulp配置proxy解决跨域问题简单解决跨域问题,具有实时重载功能,适用于偶尔的文件变动,或者H5活动页面简单的前后端交互npminitinitializationglobalinstallationgulpnpmigulp-g在本地下载gulp包npmigulp--save-dev下载gulp-webserver包npmigulp-webserver--save-dev创建一个新的gulpfile.js文件vargulp=require('gulp');varwebserver=require('gulp-webserver');gulp.task('webserver',function(){gulp.src('./').pipe(webserver({host:'localhost',port:8888,livereload:true,//livereloadopen:'./index.html',//默认浏览器启动时打开的文件directoryListing:{enable:true,path:'./'},proxies:[{source:'/api',target:'http://www.your.com'//代理的域名}]}))});//gulp4.0gulp.task('default',gulp.series(['webserver'],function(){console.log('gulpwebserverstartsuccessfullyatlocalhost:8888');}));//因为gulp已经升级到4.0,所以使用gulp.series启动。如果您使用的是gulp3.*,请将上面的代码替换为以下代码//gulp3.*gulp.task('default',['webserver'],function(){console.log('gulpwebserverstartsuccessfullyat本地主机:8888');});在项目根目录打开命令窗口,使用命令gulp开始使用:如果接口是https://www.yoururl.com/login/index,请求时使用/api/login/index