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