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