在开发时,我们的页面在localhost:8080 ,JS直接访问后端接口(如https://baidu.com或http://loacalhost:3000)会报跨域错误。
为了解决这个问题,可以在webpack.config.js中添加如下配置:
module.exports = {
//...
devServer:{
proxy:{
'/api':{
target:'<http://baidu.com>',
changeOrigin:true,
}
}
}
}
此时,在JS中请求/api/users 就会自动被代理到http://baidu.com/api/users。
如果希望请求中的Origin从8080修改为baidu.com,可以添加changeOrigin:true 。
如果要访问的是HTTPS API,那么就需要配置HTTPS证书,否则会报错。
不过,如果在target下面添加secure:false ,就可以不配置证书且忽略HTTPS报错。