本文主要介绍了详解webpack-dev-server使用http-proxy解决跨域问题,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧,希望能帮助到大家。

文档资料

webpack关于webpack-dev-server开启proxy的官方介绍

Vue-cli proxyTable 解决开发环境的跨域问题——虽然这篇是写vue的,不过用在webpack-dev-server上也是一样的

http-proxy-middleware——webpack-dev-server的实现方法其实是对这个的封装

配置http-proxy

在webpack的配置文件(webpack.config.js)中进行配置


module.exports = {
 ...此处省略一万字

 // webpack-dev-server的配置
 devServer: {
 historyApiFallback: true,
 hot: true,
 inline: true,
 progress: true,
 port: 3000,
 host: '10.0.0.9',
 proxy: {
 '/test/*': {
 target: 'http://localhost',
 changeOrigin: true,
 secure: false
 }
 }
 },

 ...此处省略一万字
};
登录后复制

上述配置中,关于http-proxy的只是 proxy: {...} 中的值

调用接口

为了方便起见,下面使用jquery封装好的ajax函数进行示范


$.ajax({
 // url: 'http://10.0.0.9:3000/test/testFetch/Login.php', // 这样不行
 url: '/test/testFetch/Login.php', // 这样行
 type: 'post',
 data: {
 app_id: '13751313169',
 password: '123456',
 user_name: 'Nicholas'
 },
 success: function(data) {
 console.log(data);
 }
});
登录后复制

proxy中的部分参数说明

'/test/*' 以及 target: 'http://localhost'

从名字就能看出,这个实际上是将匹配 '/test/*' 这种格式的API的域名重定向为 'http://localhost'

  1. 结合上面的 “调用接口” 可以看出, url: '/test/testFetch/Login.php' 这句,实际上会自动补充前缀,也就是说,url: '/test/testFetch/Login.php' 等价于 url: 'http://10.0.0.9:3000/test/testFetch/Login.php'

  2. 但是,我们使用了http-proxy进行重定向,这样的话,url: '/test/testFetch/Login.php' 等价于 url: 'http://localhost/test/testFetch/Login.php'

changeOrigin

  1. true/false, Default: false - changes the origin of the host header to the target URL

  2. 本地会虚拟一个服务端接收你的请求并代你发送该请求——这个是别人的说法

  3. 我试了一下,就算这个参数设置成 false 也有部分情况是可以的,具体原因不详,所以还是将其设置成 true 吧

secure

  1. true/false, if you want to verify the SSL Certs

pathRewrite

  1. 例子: pathRewrite: {'^/api': ''}

  2. Object-keys will be used as RegExp to match paths

  3. 我猜,这里是将 '^/api' 使用 '' 代替(只是我猜,没是成功,估计是我的正则表达式写得不行)

附上使用Fetch API的代码

上述代码与 “调用接口” 中使用 $.ajax() 实现的效果是一样的


let testAsync = async function () {
 var feeling = {
 app_id: '13751313169',
 password: '123456',
 user_name: 'Nicholas'
 };

 var fetchParams = {
 method: 'post',
 headers: {
 'Accept': 'application/json',
 'Content-Type': 'application/json'
 },
 credentials: 'include', // 将凭证也带上(例如cookies)
 body: JSON.stringify(feeling),
 };

 let temp = await fetch('/test/testFetch/Login.php', fetchParams).then(response => response.text());

 console.log(temp); // 这个就是一个json对象

 return temp;
};

let data = testAsync(); // async函数返回值是一个Promise对象

console.log(data); // 这个是一个Promise对象
登录后复制

相关推荐:

关于vue2.0设置proxyTable使用axios进行跨域请求

php 检测proxy实例代码

详解Python爬虫使用代理proxy抓取网页方法

以上就是webpack-dev-server使用http-proxy解决跨域问题详解的详细内容,更多请关注Work网其它相关文章!

08-30 04:56