跨域请求数据
/*** * 跨域 请求数据 ajax 四部曲 * */let xhr = new XMLHttpRequest();xhr.open('GET',"/api/user",true) // /api 开头的都是一个接口,像后端请求数据 true 表示异步xhr.onreadystatechange = function () { console.log(xhr.response);}xhr.send();/*** * webPack 文件 devServer 配置 * */devServer: { port: 8080, compress: true, //是否压缩代码 open:true, hot:true, // 跨域请求 // 方式一: 启动代理 proxy: { '/api':{ target: 'http://localhost:8090', secure: false, // true 表示以 https 开头 pathRewrite: {"^/api" : ""}, //你不需要传递 /api ,则需要重写路径地址 changeOrigin: true, //把请求头当中的 host 地址改成服务器的地址 } }, // 方式二 自定义中间件 before:function(app, server){ //启动一个端口号为 8080 的服务 app.get('/api/user', function(req, res) { res.json({ custom: 'response' }); }); } },
webpack.config.js 配置文件
// 配置文件const path = require('path');const {CleanWebpackPlugin} = require('clean-webpack-plugin');const HtmlWebpackPlugin = require('html-webpack-plugin')module.exports = { // 入口 entry: { index: './src/index.js', }, // 出口 output: { // filename: 'index.js', filename: '[name].js', path: path.resolve(__dirname,"dist") }, // 加载机 module: { rules: [ // js 加载机 { test: /\.js$/, use: 'babel-loader', include:path.resolve(__dirname,'src'), // 需要编译的 js 文件目录 exclude:/node_modules/, // 排除需要编译的 js 文件目录 }, ] }, // 服务器 devServer: { port: 8080, compress: true, //是否压缩代码 open:true, hot:true, // 跨域请求 // proxy: {// 方式一: 启动代理 // '/api':{ // target: 'http://localhost:8090', // secure: false, // true 表示以 https 开头 // pathRewrite: {"^/api" : ""}, //你不需要传递 /api ,则需要重写路径地址 // changeOrigin: true, //把请求头当中的 host 地址改成服务器的地址 // } // }, // 方式二 自定义中间件 before:function(app, server){ //启动一个端口号为 8080 的服务 app.get('/api/user', function(req, res) { res.json({ custom: 'response' }); }); } }, // 插件 plugins: [ new CleanWebpackPlugin(), // 清空输出目录 new HtmlWebpackPlugin({ template: './index.html', filename: 'index.html', hash: true, }), ],}