在开发时,我们的页面在localhost:8080, JS 直接访问后端接口(如 https://xyz.comhttp://localhost:3000) 会报跨域错误。
    为了解决这个问题,可以在 webpack.config.js 中添加如下配置:

    1. module.exports = {
    2. // ...
    3. devServer: {
    4. proxy: {
    5. '/api': {
    6. target: 'http://xyz.com',
    7. changeOrigin: true
    8. }
    9. }
    10. }
    11. }

    此时在 JS 中请求 /api/users就会自动被代理到 http://xyz.com/api/users
    如果希望请求中的 Origin 从 8080 修改为 xyz.com, 可以添加 changeOrigin: true
    如果要访问的是 HTTPS API, 那么久需要配置 HTTPS 证书,否则会报错。
    不过,如果在 target 下面添加 secure: false ,就可以不配置证书且忽略 HTTPS 报错。