配合webpack 和 webpack-dev-server处理
- 安装
// 安装
cnpm html-webpack-plugin --save -D
cnpm install webpack webpack-cli webpack-dev-server --save -D
- 新建src文件夹 新建文件 index.html 和 index.js
- 在index.js 发送一个请求
import axios from 'axios'axios.get('http://127.0.0.1:3001/user').then(result=>{console.log(result)
})
- 新建
webpack.config.js
并配置
// 配置webpack.config.js
var path = require('path') // 绝对路径
const HtmlWebpackPlugin = require('html-webpack-plugin');// 打包html的插件module.exports = {mode:'development', // 入口文件entry: './src/index.js',// 出口文件output: {path:path.resolve(__dirname, 'build'), // 输出文件的存放路径filename: "bundle.js", //输出文件的名称},devServer:{port:3000,progress:true,contentBase:'./build',},plugins:[ // html产出插件的应用new HtmlWebpackPlugin({template:'./src/index.html',filename: 'index.html'})]
}
- 新建一个server.js 服务 在里面写一个user接口
let express = require('express')
let app = express()app.get('/user',(req,res)=>{res.json({name:'jack'})
})
app.listen(3001,function(){console.log("server is running 3001")
})
-
在
package.json
的scripts
下配置
"dev": "webpack-dev-server --open --host 127.0.0.1 --port 3000"
这样打包完成的时候会自动开启3000端口的窗口 -
启动 server.js 服务
node server
点击加号可以新开一个终端 下拉框可以切换终端
-
切换终端 输入
npm run dev
进行打包 打包成功会自动打开3000的窗口
这时候会看到控制台报错
解决…:
在 webpack.config.js
配置 proxy
如下
proxy:{ //代理过滤 处理跨域'/':{ // 意思所有这个地址的请求都以 / 发送到 http://localhost:3001下target:'http://localhost:3001',changeOrigin:true // 改变源}
}
再重新打包
npm run dev
就会看到数据了
一些快捷链接:
Webpack打包、配置
JSONP和JQuery实现跨域
CORS 跨域资源共享