插件名:webpack-dev-server
注意该插件对webpack-cli 的新版本不兼容建议使用 "webpack-cli": "^3.3.12",
代理
使用该插件可以使用代理,
本地运行的代码是无法请求服务器方的数据,因为跨域啦,使用该插件就像是本地起了个简易服务器,服务器端的请求数据是不存在跨域的,可以让你本地其的临时服务器去请求数据,再将其数据返回到项目中
示例
完整目录为
index.js 的代码
fetch('/api/student/findAll?appkey=youkeOO1_1597126810547').then(resp =>resp.json()).then(resp =>{console.log(resp)})
webpack.config.js 的配置代码
const { CleanWebpackPlugin } = require("clean-webpack-plugin")const HtmlWebpackPlugin = require('html-webpack-plugin')var path = require("path")module.exports = {mode: "development",devtool: "source-map",output: {path:path.resolve(__dirname,'dist'),filename: "[name].[hash:5].js"},plugins: [new CleanWebpackPlugin(),new HtmlWebpackPlugin({template: "./public/index.html"})],devServer: {port: 8080,open: true,proxy: {//代理规则 当发起的请求中有符合规则webpack-dev-server 会去请求数据wepack-dev-server 请求的数据路径为 http://open.duyiedu.com/api/student/findAll?appkey=youkeOO1_1597126810547然后将其数据返回"/api": {target: "http://open.duyiedu.com",//changeOrigin: true //更改请求头中的host和origin// 默认是不会修改请求头的,此处请求的服务器会识别与请求头中的host和origin与主机名是否一致,当不一致阻止访问}}},stats: {modules: false,colors: true}}
