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